问题
Say I declare the following:
Cat elsa = new Lion();
Lion extends Cat. If I declare it this way, will elsa be a cat having All of the methods of a cat or will it be a Lion, having all of the methods of both lion and cat
This exact question is not addressed in other questions that I could find.
回答1:
The object you create is of type Lion
and has all of the attributes and methods of the Lion
object. The variable elsa
however is of type Cat
so it can only be used to access methods and attributes of a Cat
object.
So the answer to your question is that elsa
will be a Lion
that you can only treat as a Cat
unless you cast it back to a Lion
. For example:
elsa.roar(); // compile error if the roar() method is only for Lion
((Lion)elsa).roar(); // will work
来源:https://stackoverflow.com/questions/29712277/dynamic-binding-java-does-an-object-have-the-methods-of-its-declared-type-or-i