简体   繁体   English

Java Base b = new Derived(); 继承问题

[英]Java Base b = new Derived(); inheritance questions

What exactly happens when you create a new instance using : 使用以下命令创建新实例时会发生什么:

Base b = new Derived();

I cannot really understand the mechanics behind this. 我无法理解这背后的机制。

Basically, from that point the compiler sees a Base instance and in runtime the instance is of type Derived . 基本上,从那时起,编译器会看到一个Base实例,在运行时,实例的类型为Derived

In a broader explanation the Base type might be a interface, so you know by the contract what method has and what it does Polymorphism . 在更广泛的解释中, Base类型可能是一个接口,因此您可以通过契约知道什么方法具有什么以及它具有什么样的Polymorphism But you are abstracted from the implementation. 但是你从实现中抽象出来了。

The reference to b is type Base . b的引用是Base类型。 But the implementation is Derived . 但实施是Derived This means you can use it as a Base but it will behave as a Derived . 这意味着您可以将其用作Base但它将表现为Derived Doing b instanceof Derived will be true because the implementation is of type Derived 执行b instanceof Derived将为true,因为实现的类型为Derived

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM