Java:继承与声明

Java: Inheritance and declarations

以下声明有什么区别?什么时候使用它们?

ParentClass child = new ChildClass();
ChildClass child = new ChildClass();

...如果我已经有了这个:

class ChildClass extends ParentClass {}

假设您在 ParentClass 中声明了一个方法 foo(),在 ChildClass 中声明了一个方法 bar()。由于 ChildClass 扩展了 ParentClass - 它也继承了 foo() 方法。

在第一种情况下,您将无法调用 child.bar();,因为 ParentClass 没有名为 bar().

的方法

同样的事情也适用于变量,内部 类 等。有关更多信息,请参阅 Oracle documentation