Skip to content
Advertisement

How to call the method of the subclass using method of Parent class?

I have a Shape method that has two arguments first is the width and the second is the height. I have two subclasses, one is the rectangle and another is triangle. I want to call the area() the method defined in both triangle and rectangle with the help of the area() of the Shape class. I have written this piece of code but when I am calling the area() method of derived classes using the area() method of the parent class, I am getting an error. So how to do this?

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);
    }
}

Advertisement

Answer

You want to override the method and let the subclasses implement it. You do not need to call any method from Shape.area() at all!

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; }
}

With that in place, you can do:

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()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement