Abstraction in Java

Abstraction in Java

Abstraction is hiding the internal implementation and just highlighting the setup service that we are offering. As in the case of a car, relevant parts like the steering, gear, horn etc.. are shown to driver because they are necessary for driving. But the driver doesn't know the internal functioning of the engine, gears etc.. Thus, showing relevant data to the user and hiding implementation details from the user is abstraction.

Abstraction is achieved in two ways

  • Abstract class

  • Interfaces

1. Abstract class

  • Using abstract classes we can achieve 0-100% abstraction.

  • A method without a body is known as an abstract method.

  • An abstract method must always be declared in an abstract class.

  • If a regular class extends an abstract class, then the class must have to implement all the abstract methods of an abstract parent class.

  • An abstract method in an abstract class is meant to be overridden in derived concrete classes otherwise compile time error will be thrown.

  • We cannot create an object of the Abstract class.

abstract class Vehicle
{
    abstract void start();
}
class Car extends Vehicle
{
    void start()
    {
        System.out.println("Car starts with key");
    }
}
class Scooter extends Vehicle
{
    void start()
    {
        System.out.println("Scooter starts with kick");
    }
    public static void main(String[] args)
    {
        Car c = new Car();
        c.start();

        Scooter s = new Scooter();
        s.start();
    }
}

2. Interface

Interfaces are similar to abstract classes but have all the methods as abstract type. Interfaces are the blueprint of class.

  • Interface is used to achieve abstraction

  • supports multiple inheritance

  • can be used to achieve loose coupling

interface I1
{
    void show();
}
class Test implements I1
{
    public void show()
    {
        System.out.println("1");
    }
    public static void main(String[] args)
    {
        Test t= new Test();
        t.show();
    }
}

Multiple inheritance through interfaces

interface I1
{
    void show();
}
interface I2
{
    void display();
}
class Test implements I1,I2
{
    public void show()
    {
        System.out.println("1");
    }
    public void display()
    {
        System.out.println("2");
    }
    public static void main(String[] args)
    {
        Test t= new Test();
        t.show();
        t.display();
    }
}