Hi

From the below code,the example is calling the dog object through the animal reference.But i do not understand why don't it call directly through the dog class as the reference? Thanks

class Animal{

   public void move(){
      System.out.println("Animals can move");
   }
}

class Dog extends Animal{

   public void move(){
      super.move(); // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog{

   public static void main(String args[]){

      Animal b = new Dog(); // Animal reference but Dog object
      b.move(); //Runs the method in Dog class

   }
}

The question you should be asking is that why does the dog-move() method gets called even when i'm calling the move on an animal object. Java rule : methods that can be called depend on the reference type and not the object type , so whats going on here ?

Instance methods are called based on the actual class of the object used to call them. The type of the reference variable is irrelevant.

@James : i thought that applied to only overriden methods ? and also that it happens at runtime...

Hi, sorry my last post was short and not followed up - I was offline for three days. :( Here's a better answer:

Instance methods are always bound at run time, according to the actual class of the object that is used in their invocation. The object is first searched for an implementation of the method, and if none is found the superclass is searched (etc).
The type of the reference variable is just used by the compiler to ensure that the call will be valid at run time. That may be an interface, or an abstract class, but as long as it defines the method signature we know that any object the variable refers to at run time will be a concrete class with a (possibly inherited) implementation of the method.

Static methods are bound differently, and if you use a variable to invoke them then the type of the variable is used to bind the corresponding static method at compile time. Because this can be very confusing (and inconsistent with instance methods) the compiler now discorages that type of call, and encourages you to call static methods using the class name.

Edited 3 Years Ago by JamesCherrill

Comments
don't remember reading this anywhere.. really helpful answer.

Thanks for that answer , its really good ! just for the record i would like to add that class methods are nothing but the static methods. ( just in case it confuses someone , which is probable i guess when the same thing has two different names. )

Edited 3 Years Ago by somjit{}

This article has been dead for over six months. Start a new discussion instead.