【发布时间】:2019-05-09 03:38:15
【问题描述】:
以下内容来自教科书,我不知道它为什么有效。在 main 方法中,创建了一个抽象类的多个对象,这应该是不可能的。
书中给出的解释是:“这是多态性的一个例子:在运行时选择正确的volume值。”
如果无法在相关对象上调用 volume() 方法,它如何选择正确的值?
sol、sph、rec 不是 Solid 类的情况吗?如果是这样,为什么不呢? ClassA x = new ClassB();当 ClassB 扩展 ClassA 时,创建 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);
【问题讨论】:
标签: java inheritance polymorphism