I am doing OOP exercises from https://www3.ntu.edu.sg and I cant figure out one inheritance problem. We have 2 classes: superclass circle
and subclass cylinder
extends
circle
.
Circle:
public double getArea() {
return Math.PI*radius*radius;
}
public String toString() {
return "Circle Area: "+this.getArea()";
}
Cylinder extends Circle
@Override
public double getArea() {
// TODO Auto-generated method stub
return super.getArea()*2+super.getCircumference()*height;
}
@Override
public String toString() {
return "Cylinder["+super.toString+"]"+"Cylinder area="+getArea()+"]";
}
new object type Cylinder
prints super.toString()
using getArea()
from the Cylinder
class - printing both areas the cylinder
areas. How can I make it use superclass ( Circles
) getArea()
in super.toString
?
Thanks!
During runtime this
represents the current instance of the object and this is a Cylinder
with his getArea()
method. Therefore inheritance does not help us here.
A workaround can be to change the Circle
class this way:
private double getCircleArea() {
return Math.PI*radius*radius;
}
public double getArea() {
return getCircleArea();
}
public String toString() {
return "Circle Area: " + this.getCircleArea();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.