java - 如何使用父类的方法调用子类的方法?
问题描述
我有一个 Shape 方法,它有两个参数,第一个是宽度,第二个是高度。我有两个子类,一个是矩形,另一个是三角形。我想借助 Shape 类的 area() 调用在三角形和矩形中定义的方法 area()。我已经编写了这段代码,但是当我使用父类的 area() 方法调用派生类的 area() 方法时,出现错误。那么如何做到这一点呢?
public class Shape {
double width, height;
public Shape(double w, double h)
{
this.height = h;
this.width = w;
}
public void area(Object shape){ // area method of parent class
shape.area(); // here I am getting error.
}
}
class triangle extends Shape{
triangle tri;
public triangle(double w, double h) {
super(w, h);
}
public void area()// area method of derived class
{
double area = (1/2)*width*height;
System.out.println("The area of triangle is: "+area);
}
}
class rectangle extends Shape{
rectangle rect;
public rectangle(double w, double h) {
super(w, h);
}
public void area() // area method of derived class
{
double area = width*height;
System.out.println("The area of rectangle is: "+area);
}
}
解决方案
您想覆盖该方法并让子类实现它。您根本不需要调用任何方法Shape.area()
!
public abstract class Shape {
float width, height;
Shape(float width, float height) {
this.width = width;
this.height = height;
}
public abstract float area();
}
public class Rectangle extends Shape {
public Rectangle(float width, float height) {
super(width, height);
}
@Override
public float area() { return width * height; }
}
public class Triangle extends Shape {
public Triangle(float width, float height) {
super(width, height);
}
@Override
public float area() { return (width*height) / 2; }
}
有了它,您可以执行以下操作:
Shape shape = new Triangle(50f, 50f);
float areaOfTri = shape.area(); // dispatches to Triangle.area()
shape = new Rectangle(50f, 50f);
float areaOfQuad = shape.area(); // dispatches to Rectangle.area()
推荐阅读
- django - 如何使用 django 显示从数据库中检索到的数据
- python - AttributeError:“NoneType”对象没有属性“get_text”。为什么我会收到此错误?
- android - 即使应用程序关闭,如何在 API >= 26 中执行定期后台工作?
- php - 如何从数据库中读取数据更改它们并更新数据库
- azure-data-factory - Azure 数据工厂复制活动休息 API JSON 响应日期格式不正确
- python-3.x - 数据集的随机子集
- scapy - DHCP欺骗攻击后继续受害者的网络连接
- excel - 有没有办法更新用户表单以在列表框中更新
- python - 如果组合框中的特定项目被调用,则确定函数/方法
- ruby-on-rails - 如何从 CSV 导入图像并使用 ActiveStorage 附加到模型?