Abstraction in Java
Abstraction in Java
Abstraction in Java is the process of hiding the implementation details and only showing the essential
functionality or features to the user. This helps simplify the system by focusing on what an object does
rather than how it does it. The unnecessary details or complexities are not displayed to the user.
double length;
double width;
2
}
// Another example of Abstract Class declared
// Abstracted class
class Dog extends Animal
{
public Dog(String name)
{
super(name);
}
// Abstracted class
class Cat extends Animal
{
public Cat(String name)
{
super(name);
}
// Driver Class
public class Geeks
{
3
public static void main(String[] args)
{
Animal myDog = new Dog("ABC");
Animal myCat = new Cat("XYZ");
myDog.makeSound();
myCat.makeSound();
}
}
Interface
Interfaces are another method of implementing abstraction in Java. It is a collection of abstract methods.
The interface is used to achieve abstraction in which you can define methods without their
implementations (without having the body of the methods). An interface is similar to the class.
Example:
interface Animal
{
public void eat();
public void travel();
}
public class MammalInt implements Animal
{
public void eat()
{
System.out.println("Mammal eats");
}
4
{
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Output
Mammal eats
Mammal travels
5
Extending Java Interfaces
An interface can extend another interface in the same way that a class can extend another class. The
extends keyword is used to extend an interface, and the child interface inherits the methods of the
parent interface.
interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
6
public void overtimePeriod(int ot) {}
Output
Home team: India
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define
the three methods from Football and the two methods from Sports.
import java.io.*;
interface intfA
{
void geekName();
}
interface intfB
{
void geekInstitute();
}
7
{
System.out.println("CSE");
}
Output
Rohit
JIIT
CSE