I am learning Java using the book Java: The Complete Reference. Currently I am working on the topic of abstract classes.
Please Note: There are similar questions on stackoverflow. I searched them but I couldn't understand the concept.
If I run the below program, it produces the correct output, but I didn't understand the concept.
What is the need of reference variable of an Abstract class here. I can get the output without the reference variable of an abstract class.
First I ran the below program and got the desired output.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an an abstract method
abstract double area();
}
class Rectangle extends Figure {
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 Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
And I tried the below code without creating/using abstract class reference.
class AbstractAreas {
public static void main(String args[]) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
// Figure figref;
// figref = r;
System.out.println("Area is " + r.area());
// figref = t;
System.out.println("Area is " + t.area());
}
}
It also gave the same output as the first program.
Can anyone please explain what is the need of calling "area method" using abstract class reference.
It's meant simply as a demonstration that even though you declared the variable as the abstract type, you can assign an instance of a concrete subclass to it and get the overriden behavior from the subclass.
Practical use example would be if you needed a collection of them:
List<Figure> figureList = new ArrayList<Figure>();
figureList.add(new Rectangle(9, 5));
figureList.add(new Triangle(10, 8));
for (Figure f : figureList) {
System.out.println(f.area());
}
Or if you want to pass any subclass of Figure
to a method that used the area()
:
public void printArea(Figure f) {
System.out.println("Area is: " + f.area());
}
...
myObject.printArea(new Rectangle(9, 5));
myObject.printArea(new Triangle(10, 8));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With