这叫什么? "allows the programmer to call a method on a subclass even though they only have a reference t



我认为这是多态性或继承。可以给我一个基本的例子吗

public class ParentClass {
    public void doSomething() {
        System.out.println("Parent Class Method");
    }
}
public class ChildClass extends ParentClass {
    public void doSomething() {
        System.out.println("Child Class Method");
    }
}

现在在你的主代码中你可以做如下的事情:

ParentClass class = new ChildClass();
class.doSomething();

这会打印出"ChildClass Method",因为ChildClass方法覆盖了ParentClass方法。

  • "ChildClass extends ParentClass"是继承的一个例子。
  • "ParentClass class = new ChildClass();"是一个例子多态性。

还困惑?

您的特殊情况称为动态多态性。(方法重载将是静态多态性的一种情况)。

相关内容

最新更新