The following is from a textbook, and I don't know why it works. In the main method, several objects of an abstract class are created, which shouldn't be possible.
The explanation the book gives is: "This is an example of polymorphism: The correct value of volume is selected at runtime."
How does it select the correct value if the volume() method cannot be called on the object in question?
Is it the case that sol, sph, and rec are not of class Solid? If so, why not? ClassA x = new ClassB(); creates an object of ClassA when ClassB extends ClassA.
public abstract class Solid {
private String name;
public Solid(String solidName) {name = solidName;}
public String getName() {return name;}
public abstract double volume();
}
public class Sphere extends Solid {
private double radius;
public Sphere(String sphereName, double sphereRadius) {
super(sphereName);
radius = sphereRadius;
}
public double volume() {
return (4.0/3.0) * Math.PI * radius * radius * radius;
}
public class RectangularPrism extends Solid {
private double length;
private double width;
private double height;
public RectangularPrism(String prismName, double l, double w, double h) {
super(prismName);
length = l;
width = w;
height = h;
}
public double volume() {
return length * width * height;
}
public class SolidMain {
public static void printVolume(Solid s) {
System.out.println("Volume = " + s.volume() + " cubic units.");
}
public static void main(String[] args) {
Solid sol;
Solid sph = new Sphere("sphere", 4); //is sph an object of type Solid?
Solid rec = new RectangularPrism("box", 3, 6, 9);
int flipCoin = (int) (Math.random()*2); //random 0 or 1
if (flipcoin == 0) {
sol = sph;
} else {
sol = rec;
} printVolume(sol);