Mr.Joker
Mr.Joker

Reputation: 13

how to prevent inheritance chain in java

I have a problem with inheritance chain in java I have an interface Geometry, a class Circle implements Geometry,and a class Cylinder extends Circle. Because Circle haven't Volume, I return it to 0. When Cylinder extends Circle, Volume return V = PI * Radius * Radius * Height But I create instance of Cylinder is cy, when it call getVolume(), it return 0 of Circle. How does it call getVolume() itself, not Circle?? Thanks. This is my code:

public interface Geometry {

    public double getArea();

    public double getVolume();
}

class Circle implements Geometry {

    public double R;

    public double getArea() {
        return Math.pow(R, 2) * Math.PI;
    }

    public double getVolume() {
        return 0; // because not volume of Circle
    }
}

class Cylinder extends Circle {

    public double Height;

    //lateral area of Cylinder
    public double getArea() {
        double s = super.getArea();
        return 2 * s + 2 * Math.PI * super.R * this.Height;
    }

    public double getVolume() {
        return Math.PI * Math.pow(R, 2) * Height;
    }
}

public class Main {

    public static void main(String[] args) {
        Cylinder cy = new Cylinder();
        cy.R = 1;
        System.out.println(cy.getArea()); // 6.28
        System.out.println(cy.getVolume()); // 0 Wrong!!!
    } 
}

Upvotes: 0

Views: 144

Answers (3)

Aron
Aron

Reputation: 15772

Inheritance is overused by beginner programmers

Your idea to use inheritance here breaks many many rules in OOP. The most basic of which is that, a cylinder is not a cycle.

There are other mechanisms for code re-usage in OOP, but beginners gravitate towards inheritance because it is obviously FOR re-usage.

Encapsulation and Composition

In this case, I would encourage you to use composition, which is a consequence of encapsulation.

In this case I would encourage you to make a class called Prism that contains two properties, Height and Face, the second of which is where you place your Circle.

Upvotes: 0

chrisl08
chrisl08

Reputation: 1658

I think your problem is not the Circle's getVolume called. The method called is the Cylinder's, but the Height property is 0, hence the 0 return value.

You need to set the Height property of your Cylinder instance (cy), as in:

 cy.Height = 3.00;

Upvotes: 0

coder
coder

Reputation: 4466

Its not returning the getVolume() of circle, but as you have not set the height the volume is coming as Zero return Math.PI * Math.pow(R, 2) * Height; You can confirm this by putting a system.out.println statement in the method.

But in any case this hierarchy is incorrect, you should not extend Cylinder with circle as cylinder is not a circle. Inheritance is used to make a specific type from a generic type like dog out of animal, cylinder and circle are not related in that sense , so you are misusing inheritence

Upvotes: 2

Related Questions