We use inheritance in Java to abstract out similar behavior in a superclass and let all sub classes inherit it. One of the advantages of this is that , we now have only one copy of the method to maintain (i.e in the superclass).
Class Animal
{
public void makeNoise()
{
}
public void sleep()
{
}
}
Class Cat extends Animal
{
// Override the makeNoise method
public void makeNoise()
{
}
}
Class someClass
{
public static void main(String args[])
{
Cat fluffy = new Cat();
fluffy.sleep();
}
}
I am trying to understand how the Java compiler knows of the sleep()
method for a Cat
type reference. There can't be a copy of the method in the Cat
subclass (it defeats the purpose of having it in the superclass and letting all subclasses inherit from it). Is this information stored in some other place ?
The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
The most important use of inheritance in Java is code reusability. The code that is present in the parent class can be directly used by the child class. Method overriding is also known as runtime polymorphism. Hence, we can achieve Polymorphism in Java with the help of inheritance.
The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.
When the compiler sees fluffy.sleep()
it first looks in the Cat
class for a public instance method called sleep
that takes no parameters. Since it doesn't find it, it moves up the inheritance chain to Animal
, and does the same check on Animal
. It finds it there, so all is good.
This information isn't really "stored" anywhere except in the code, and then the Java byte code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With