Can we create an object of an abstract class in Java?


No, we can't create an object of an abstract class. But we can create a reference variable of an abstract class. The reference variable is used to refer to the objects of derived classes (subclasses of abstract class).

An abstract class means hiding the implementation and showing the function definition to the user is known as Abstract class. A Java abstract class can have instance methods that implement a default behavior if we know the requirement and partially implementation we can go for an abstract class.

Example

Live Demo

abstract class Diagram {
   double dim1;
   double dim2;

   Diagram(double a, double b) {
      dim1 = a;
      dim2 = b;
   }
      // area is now an abstract method
      abstract double area();
}

class Rectangle extends Diagram {
   Rectangle(double a, double b) {
      super(a, b);
   }
   // override area for rectangle
   double area() {
      System.out.println("Inside Area for Rectangle.");
      return dim1 * dim2;
   }
}

class Triangle extends Diagram {
   Triangle(double a, double b) {
      super(a, b);
   }
   // override area for triangle
   double area() {
      System.out.println("Inside Area for Triangle.");
      return dim1 * dim2 / 2;
   }
}

public class Test {
   public static void main(String args[]) {
      // Diagram d = new Diagram(10, 10); // illegal now
      Rectangle r = new Rectangle(9, 5);
      Triangle t = new Triangle(10, 8);

      Diagram diagRef; // This is OK, no object is created
      diagRef = r;
      System.out.println("Area of Rectangle is: " + diagRef.area());
      diagRef = t;
      System.out.println("Area of Triangle is:" + diagRef.area());
   }
}

In the above example, we cannot create the object of type Diagram but we can create a reference variable of type Diagram. Here we created a reference variable of type Diagram and the Diagram class reference variable is used to refer to the objects of the class Rectangle and Triangle.

Output

Inside Area for Rectangle.
Area of Rectangle is: 45.0
Inside Area for Triangle.
Area of Triangle is:40.0
raja
Published on 12-Jun-2019 18:39:52
Advertisements