Abstraction means specifying only what has to be done but not how it has to be done. We can achieve abstraction in Java by –
  • Interfaces
  • Abstract Classes
Below example explains how to use abstract classes in Java. In below example, Car is an abstract class.

package abstraction;

public class AbstractTest {

    public static void main(String [] args){
        //Below statement throws error saying Car is abstract.. can not instantiate
        //Car c = new Car()

        //Below statement will work..
        HatchbackCar c1 = new HatchbackCar();
        c1.move();

    }
}

abstract class Car{
    public abstract void move();
}

class HatchbackCar extends Car{
    public void move(){
        System.out.println("Hatchback move method");
    }
}
Here is the output of above code.

Hatchback move method

Web development and Automation testing

solutions delivered!!