Abstract Class

An abstract class can have abstract method without body and it can have methods with implementation also. abstract keyword is used to create a abstract class and method. Abstract class can’t be instantiated. It is mostly used to provide base for subclasses to extend and implement the abstract methods and override or use the implemented methods in abstract class.

 

Abstract Methods

An abstract class can have abstract methods. A abstract method is declared by adding the abstract keyword in front of the method declaration. If a class has an abstract method, it should be declared abstract as well.

// Abstract class
public abstract class AbstractClass {
  // Abstract method
  public abstract void abstractMethod();
}

 

Example

// abstract class example 
abstract class BaseClass{

  // Abstract class can contain constructor
  BaseClass() { 
    System.out.println("Base Constructor Called"); 
  } 
 
  // Non Abstract method
  public void disp(){
    System.out.println("Concrete method");
  }

  // Abstract Method 
  abstract public void disp2();
}

// Subclass inheriting from MyClas
class SubClass extends BaseClass{

  // Derived class constructor
  SubClass() { 
    System.out.println("Derived Constructor Called"); 
  } 

  // Must Override this method while extending 
  public void disp2()
  {
    System.out.println("Overriding abstract method");
  }

  public static void main(String args[]){
    SubClass obj = new SubClass();
    obj.disp2();
  }
}

 

Important Points

  • Abstract class in java can’t be instantiated.
  • We can use abstract keyword to create an abstract method, an abstract method doesn’t have body.
  • If a class have abstract methods, then the class should also be abstract using abstract keyword, else it will not compile.
  • It’s not necessary to have abstract class to have abstract method.
  • Subclass of abstract class must implement all the abstract methods unless the subclass is also an abstract class.
  • Abstract class can implement interfaces without even providing the implementation of interface methods.
  • Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.
  • Abstract class can have final, non-final, static and non-static variables.

 

Related Post