Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the java compiler know of inherited methods?

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 ?

like image 439
Chiseled Avatar asked Jul 13 '15 17:07

Chiseled


People also ask

How are methods inherited in Java?

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.

How is inheritance implemented achieved in Java?

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.

How do you inherit variables in Java?

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.


1 Answers

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.

like image 69
Jashaszun Avatar answered Oct 24 '22 04:10

Jashaszun