【问题标题】:Java: Inheritance and declarations [duplicate]Java:继承和声明
【发布时间】:2016-07-20 06:45:18
【问题描述】:

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

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

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

class ChildClass extends ParentClass {}

【问题讨论】:

  • 第一个实例可以访问子父方法、变量等。第二个实例将是一个独立实例,只能访问它自己的方法、变量等。

标签: java inheritance declaration


【解决方案1】:

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

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

同样适用于变量、内部类等。有关详细信息,请咨询Oracle documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2021-07-07
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2012-10-19
    相关资源
    最近更新 更多