Abstraction in JAVA

Abstraction in JAVA

Abstraction is a process of hiding the implementation details from the user.

For example, let us say you logged into your PC and now opening your browser. Let us say you now type www.google .com, you will be straight brought to google's homepage, but what you have not seen is that first google.com gets converted into an IP address(like 128.38.8.4)  and loads of other things go on in the background which the user is not aware of. This is abstraction and is just a beautiful way of keeping things simple in life!

Abstract Class

A class which contains the abstract keyword in its declaration is known as abstract class.

  1. We can create an abstract class by using abstract keyword.
  2. A class that has at least one abstract method, then the class must be declared abstract.
  3. If a class is declared abstract, it cannot be instantiated that is we cannot create an object of the abstract class.
  4. An abstract class may or may not have abstract methods.
  5. An abstract class can be extended by another abstract class.
  6. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Use of Abstract Class

We use abstract classes when we know the methods, but we yet don't know how are they going to be implemented.

Note :- When we mark a method as abstract in the abstract class, it means that is the bare minimum functionality that the program must provide.

Let us take an example, we have a vehicle we know that any vehicle be it a bike, car or bus has top speed and show() method whether vehicle is a car or bike. You can see below that abstract class can inherit another abstract class. Now assuming all cars have unique features, so we declared the feature() method. One thing to notice is that all methods declared as abstract have to be implemented.

public class Main{

    public static void main(String []args){
        Car t = new Tesla();
        t.common_feature();
        t.show();
        t.top_speed();
        t.feature();
    }
}

abstract class Vehicle{
    public void common_feature(){
        System.out.println("All vehicles have accelerator and breaks");
    }
    public abstract void top_speed();
    public abstract void show();
}

abstract class Car extends Vehicle{

    public abstract void feature();
    public void show()
    {
        System.out.println("CAR - VEHICLE");
    }

}

class Tesla extends Car{

    public void top_speed(){
    System.out.println("Tesla has a top speed of 250km/h");
    }

    public void feature(){
        System.out.println("Tesla is an Electric Car and is Automatic too");
    }
}

Output

All vehicles have accelerator and breaks
CAR - VEHICLE
Tesla has a top speed of 250km/h
Tesla is an Electric Car and is Automatic too

Advantages of Abstraction

  1. It reduces the complexity of viewing the things.
  2. Avoids code duplication and increases reusability.
Share Me!
  •  
  •  
  •  
  •  
  •  
  •