Reputation: 13
I have a total of three classes. Main, Animal (Superclass) and Cat (Subclass). When I tried to call the whatIsTheClass() method, I didn't understand the output "Cat". I was expecting to see the output "Animal". The reason why I expected the output "Animal" is because I believe the method whatIsTheClass() is called from an Animal object and not a Cat object as the Subclass does not contain this method.
Main class:
package com.example.java;
public class Main {
public static void main(String[] args) {
Animal cat = new Cat();
}
}
Cat class:
package com.example.java;
public class Cat extends Animal {
public Cat() {
super();
whatIsTheClass();
}
}
Animal class:
package com.example.java;
public class Animal {
public void whatIsTheClass() {
System.out.println(this.getClass().getSimpleName());
}
}
My understanding is that in inheritance, the Subclass does not copy the methods from the Superclass. If the called to method is not defined in the Subclass object, it will look for the called to method in the Superclass object. And if the called to method is defined in the Superclass object, it will be called from there. In this case, because the Subclass does not define it's own whatIsTheClass() method, it must have used the whatIsTheClass() method that is defined in the Superclass object. But if whatIsTheClass() was called from the Superclass object, why did it return the name of the Subclass rather than the name of the Superclass?
Upvotes: 1
Views: 1285
Reputation: 178343
The method whatIsTheClass
may be defined in Animal
, but in which class's code getClass()
is called makes no difference. It's all about the runtime type of the object, as stated in the Javadocs for getClass()
:
Returns the runtime class of this
Object
.
The runtime type of the object specified by cat
is Cat
.
This is also why no class has to override getClass()
just to return the proper Class
object. (The method getClass()
is final
anyway.)
Upvotes: 2
Reputation: 802
When an object of Cat class is created, a copy of the all methods and fields of the superclass acquire memory in this object. That is why, by using the object of the subclass you can also access the members of a superclass. Please note that during inheritance only object of subclass is created, not the superclass.
Upvotes: 0