Abstraction in Java

Abstraction In Java

Abstraction means hiding certain details and showing only essential information to the user. It can be achieved with abstract classes or interfaces. The abstract class cannot be used to create objects. We can achieve pure abstraction using an interface.

Abstract Class

  • We must declare an abstract class with an abstract keyword.
  • It can’t be instantiated. We can’t create an object of it.
  • It can have both abstract and non-abstract methods.
  • It can have constructors and static methods.
  • It can have final methods which will force the subclass not to change the method’s body.
Info

Note: We can create abstract properties and functions in abstract class.

Abstract Method

Abstract methods are the methods that it declared without implementation. It doesn’t have a body.

abstract void walk();

Example

public class AbstractWork {
    public static void main(String[] args) {
        HarryPoter hp = new HarryPoter();
        hp.bookPages();
        hp.printBookDetails();
    }
}

abstract class Book{
    public abstract void bookPages();

    public void printBookDetails(){
        System.out.println("Book Details");
    }

}

class HarryPoter extends  Book{
    public void bookPages(){
        System.out.println("Book Pages");
    }
}
Show Output