Abstract Class in Java

Abstract class and Abstract Method

 

Abstract classes are useful when you want to create a superclass that only defines a generalized form that will be shared by its subclasses, and each class provides the implementation of its own.

 

An abstract method is a method without a method body. It only contains the method header.

 

An Abstract class contains 0 or more abstract methods. It can contain non-abstract methods too.

 

Creating abstract class

 

To declare a class as abstract, just add the keyword “abstract” in the class declaration before the class keyword.

 

An abstract class can not be instantiated with new operator.

 

Abstract can not be used with constructors or static methods.

 

Any subclass of an abstract class must override all the abstract methods of it or declare itself as abstract.

 

public abstract class ClassA {

  abstract public void show();
}

public class ClassB extends ClassA{

  public void show(){
    System.out.println("Concrete ClassB.show() called");
  }
}

public class AbstractExample {

  public static void main(String[] args) {
    ClassB objB = new ClassB();
    objB.show();
  }

}

 

In the above code snippet, abstract class ClassA contains an abstract method show(). ClassB overrides this abstract method and provides a concrete implementation.

 

Here is the output form the above program :

Concrete ClassB.show() called

 

Create objects using abstract class reference using run-time polymorphism

 

Although abstract classes can not be used to instantiate objects, we can create a reference to an abstract class and point it to subclass object because of run-time polymorphism.

 

Here is an example code that uses run-time polymorphism to create a subclass object using an abstract class reference.

 

public abstract class ClassA {

  abstract public void show();
}

public class ClassB extends ClassA{

  public void show(){
    System.out.println("Concrete ClassB.show() called");
  }
}

public class AbstractExample {

  public static void main(String[] args) {
    ClassA refA;
    refA = new ClassB();
    refA.show();
  }

}


 

Abstract and final

 

We can not declare a class both abstract and final.

 

This is because, the keyword abstract represents an incomplete class which depends on the subclasses for its implementation. Creating a subclass is compulsory for a abstract class .

 

final keyword presents inheritance. So, we can not create a subclass of a final class.

 

Therefore both abstract and final can not be used together for the same class.

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags