What are abstract classes in Java?



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

  • Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
  • But, if a class has at least one abstract method, then the class must be declared abstract.
  • If a class is declared abstract, it cannot be instantiated.
  • To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
  • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Declaring an abstract class:

To declare an abstract class just use the abstract keyword before it.

abstract class AbstractExample {
   public abstract void sample();
   public abstract void demo();
}

Since you cannot instantiate an abstract class to use its methods extend the super class and override the implementations of those methods and use them.

Example

Live Demo

abstract class SuperTest {
   public abstract void sample();
   public abstract void demo();
}
public class Example extends SuperTest{
   public void sample(){
      System.out.println("sample method of the Example class");
   }
   public void demo(){
      System.out.println("demo method of the Example class");
   }
   public static void main(String args[]){
      Example obj = new Example();
      obj.sample();
      obj.demo();
   }
}

Output

sample method of the Example class
demo method of the Example class

Advertisements