首页 > 解决方案 > 如何使用父类的方法调用子类的方法?

问题描述

我有一个 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);
    }
}

标签: javaoop

解决方案


您想覆盖该方法并让子类实现它。您根本不需要调用任何方法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()

推荐阅读