Abstract Class in Java
Abstract Keyword in Java
Recall, a class in which a method cannot be implemented or a developer cannot provide definition. The object oriented language provide the concept of defining abstract method. The class having an abstract method is to be defined as an abstract class.
Java provides abstract keyword to defined an abstract method as well as an abstract class. Now in Java, the two-dimensional figure class is implemented as follows:
abstract class TwoDFigure {
//Fields to store dimension of the two-dimension figure
protected int d1;
protected int d2;
//Constructors to initialize the dimensions
public TwoDFigure(int d1,int d2) {
this.d1 = d1;
this.d2 = d2;
}
//Method to compute the area of the figure
//no definition, i.e. abstract method
abstract public void computeArea();
}
The abstract class can only be used by inheriting it. However, its object cannot be created i.e. cannot be instantiated. Recall, Inheritance represents a IS_A relationship. Therefore, a Triangle is a two-dimensional figure, a Rectangle is also a two-dimensional figure. The following code demonstrate how to use the abstract class.
class Rectangle extends TwoDFigure {
public Rectangle(int length,int breadth) {
super(length,breadth);
}
public void computeArea() {
int area;
area = d1*d2;
System.out.println("Area of Rectangle : " + area);
}
}
class Triangle extends TwoDFigure {
public Triangle(int base,int height) {
super(base,height);//Pass Parameters to Super class
}
//Overrides abstract method
public void computeArea() {
double area;
area = (1.0/2.0) *d1*d2;
System.out.println("Area of Triangle : " + area);
}
}
Recall, in Java the reference of the super class can refer to the objects of the sub classes and then it calls the method of that class. It is used to achieve runtime polymorphism. In Java, It is called Dynamic Method Dispatch.
The Rectangle and the Triangle class can be tested by defining a class with the main method as follows:
class Test {
public static void main(String[] args) {
//Create a Reference variable of TwoDFigure class
TwoDFigure figure;
//Refers to object of Rectangle class
figure = new Rectangle(10,20);
//Calls computeArea() version of Rectangle class
figure.computeArea();
//Refers to object of Triangle class
figure = new Triangle(10,20);
//Calls computeArea() version of Rectangle class
figure.computeArea();
}
}
The abstract method is a unimplemented method in an abstract class. It is provided implementation in the respective sub classes. It archives runtime Polymorphism.
Imagine the cut-copy and the paste operation in software. Their implementation varies from one software to another software.
Abstract Class in Java
Reviewed by Syed Hafiz Choudhary
on
September 13, 2023
Rating:
No comments: