0

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.

aaa
  • 99
  • 1
  • 1
  • 7
  • Why don't you try and see ? – Nir Alfasi Apr 18 '15 at 02:43
  • I tried and it seems to me as if it takes on the declared type. Is that right? I just want to make sure i'm not missing anything. – aaa Apr 18 '15 at 02:45
  • You're not missing anything, declaring elsa as a Cat restricts it only to methods that are implemented by Cat (but which can be overriden by Lion). – Nir Alfasi Apr 18 '15 at 02:52
  • Assigning a `Lion` object to a `Cat` reference doesn't change what methods the object has (at run time). It changes what methods the compiler will let you access (at compile time). If all that mattered was that the object has the methods then java would have duck typing. It doesn't. You can hack your way around this problem by casting but just makes people wonder why you bothered making a `Cat` class in the first place. The whole point of the `Cat` type was to say, "as long as you can do what a cat does you can go here and just be a `Cat`, Nothing will ask you to do more then that. – candied_orange Apr 18 '15 at 03:57

1 Answers1

2

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
Always Learning
  • 5,510
  • 2
  • 17
  • 34