Dynamic Binding Java. Does an object have the methods of its declared type, or its actual type? [duplicate]

纵饮孤独 提交于 2020-01-06 19:06:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!