【问题标题】:Creating object of abstract class in Java textbook [duplicate]在Java教科书中创建抽象类的对象[重复]
【发布时间】: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


    【解决方案1】:

    请了解 OOP 的基本概念。

    了解什么是多态后你会得到答案。

    这里的 sol,sph,rec 只是引用而不是对象。

    sph 指向您所写的球体对象 (Solid sph = new Sphere("sphere", 4)) ,球体对象由 new Sphere("sphere",4) 和 '=' 运算符点创建sph 对球体对象的引用。因此,它调用自己的方法并完成计算。

    在rec的情况下也会发生类似的事情。

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多