Search code examples
javainheritancecompiler-construction

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 ?


Solution

  • 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.