Java Abstraction


Java Abstraction is a process of hiding the implementation details and showing only the functionality to the user.

In abstraction, the user will have the information on what the object does instead of how it does it.

We can achieve abstraction in java using Abstract class and interface.


Abstract class: An abstract class is a class which contains the abstract keyword in its declaration.

Syntax:

abstract class AbstractClass{}

Abstract method: An abstract method is declared with abstract keyword and does not have any implementation/body.

Syntax:

abstract void AbstractMethod();

Note: Instead of curly braces, an abstract method will have a semi colon (;) at the end.

It may or may not contain abstract methods.

It cannot be instantiated.

A class must be declared abstract if it has at least one abstract method.

Example:

class Animal
{
    // This will give a compile time error
    abstract void eat();  
}

If we inherit an abstract class then we have to provide implementations to all the abstract methods in it.

We can use an abstract class by inheriting it from another class and providing the implementations to all the abstract methods in it.


Example: Let Animal is an abstract class, its implementation is provided by the classes Lion and Cow. Factory method provides the object of the implementation class. If you create an instance of the Lion class, eat() method of Lion class will be invoked.

abstract class Animal
{  
    abstract void eat();  
}

class Lion extends Animal
{  
    void eat()
    {
        System.out.println("Eats flesh");
    }
}

class Cow extends Animal
{  
    void eat()
    {
        System.out.println("Eats grass");
    }
}

class AbstractionExample
{  
    public static void main(String args[])
    {  
        Animal l=new Lion();
        l.eat();            // Eats flesh
        Animal c=new Cow();
        c.eat();            // Eats grass
    }
}