【问题标题】:A superclass reference shouldn't be able to call methods exclusive to it's subclass but超类引用不应该能够调用它的子类独有的方法,但是
【发布时间】:2015-03-01 22:47:04
【问题描述】:

但是,如果超类有一个抽象方法,并且该方法在它的子类中实现,这是具体的,我们仍然可以使用超类的 Object 调用子类的方法实现。

怎么会?

对于重载方法也是如此,即使您使用超类的引用来调用子类的实现,也会调用它。

让我在这里更具体...

假设 Animal 是一个超类,而 Dog 是一个子类。 现在,我愿意:

Animal a = new Dog();

这意味着 a 是对动物类的引用,对吧?

现在,如果我这样做,a.function(); (假设该函数在 Animal 中定义并在 Dog 中被覆盖),Animal 的版本应该被称为 a 是对动物的引用,但反过来。

【问题讨论】:

  • 因为它不是子类独有的?
  • 这就是抽象方法和多态性的全部意义...... 调用者不需要知道实现的细节......
  • 重载与覆盖不同。考虑到编辑,我不再知道您的问题是什么。
  • Animal a = new Dog(); a 是对 Animal 对象还是 Dog 对象的引用?
  • 所以,我猜它是Animal 类型的引用,但指向Dog 对象。

标签: java inheritance


【解决方案1】:

这意味着超类不能调用子类中定义的方法,因为超类不知道它们。对于抽象方法,超类知道它们,因此可以调用它们。非抽象和非最终方法也会发生这种情况:它们可以被子类修改而不会注意到超类,而超类仍然可以正常工作。

您所描述的是编译时间和执行时间(也称为运行时间)之间的差异。在编译时,变量只能调用在声明变量的类型上定义的方法,例如Animal animal 然后animal 变量只能调用在Animal 类中定义的方法。在执行时,方法的执行将由属于对象引用实例的类处理,例如Animal animal = new Dog(); 然后animal 行为将由Dog 类中声明的行为定义。

例子:

public class Animal {
    abstract void breath();
}

public class Dog extends Animal {
    @Override
    public void breath() {
        System.out.println("Dog breathing");
    }

    public void bark() {
        System.out.println("woof!");
    }
}

public class Client {
    public static void main(String[] args) {
        //animal variable is of type Animal
        //and initialized as a Dog object reference
        Animal animal = new Dog();

        //dog variable is of type Dog (also an Animal)
        //and initialized as a Dog object reference
        Dog dog = new Dog();

        animal.breath();
        dog.breath();

        //line below throws a compiler exception
        //since animal is declared as type Animal
        //not all Animals know how to bark
        animal.bark();

        //line below compiles fine
        //since dog is declared as type Dog
        //and Dog's know how to bark
        dog.bark();
    }
}

【讨论】:

    猜你喜欢
    • 2018-08-22
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2011-11-22
    • 2020-09-21
    • 2015-04-23
    相关资源
    最近更新 更多