Search code examples
javasubclasssuperclass

Different Types of Subclass Objects with One Superclass


So I have a superclass GeoFig class, and two subclasses Cylinder and Sphere. I want to include one method in the superclass to calculate the volume(called setVolume), but each subclass has a different formula for calculating the volume. Through the subclass' constructors I will setVolume and will also getVolume. How do I do this?


Solution

  • My Java is very rusty, so consider any code here to be pseudo-code just to demonstrate the concepts...

    You're not modeling the objects in code correctly. The code should match the real-world concepts being modeled. So let's consider those real-world concepts.

    What is a GeoFig?

    What does one look like? If you held one in your hand, what shape would it be? There's no answer to that, because it's not a concrete object. It's a conceptual or abstract object. So it should be an abstract class:

    abstract class GeoFig { }
    

    What attributes describe a GeoFig?

    Does it have a length? A width? A radius? Not really, no. But for the purposes of being an object in 3-dimensional space we can assume that it has a volume. We just don't know how to calculate that volume:

    abstract class GeoFig {
        abstract double getVolume();
    }
    

    Now we have our parent class.

    What is a Cylinder?

    It's a geometric object with a volume, so we can inherit from the parent class:

    class Cylinder inherits GeoFig {
        public double getVolume() {
            return 0;
        }
    }
    

    How do we calculate the volume of a Cylinder?

    π * r^2 * h
    

    But we don't have r or h yet...

    What attributes describe a Cylinder?

    It has a height and a radius. In fact, it must have these to exist at all. So it requires them for object construction:

    class Cylinder inherits GeoFig {
    
        private final double height;
        private final double radius;
    
        public Cylinder(double height, double radius) {
            this.height = height;
            this.radius = radius;
        }
    
        public double getHeight() {
            return this.height;
        }
    
        public double getRadius() {
            return this.radius;
        }
    
        double getVolume() {
            return 0;
        }
    }
    

    (This assumes immutability. Make appropriate changes if you want to be able to change the dimensions of a Cylinder.)

    Now we can also calculate the volume:

    double getVolume() {
        return Math.PI * this.radius * this.radius * this.height;
    }
    

    Repeat the same logical process for any other shapes.