class Dog { public void bark() { System.out.println("Dog bark"); } }

class Hound extends Dog {
    public void bark() { System.out.println("Hound bark"); }
    public void sniff() { System.out.println("Hound sniff"); }
    }

public class CastingMethodCall {
        public static void main(String r[]) {       
            ((Dog)new Hound()).bark();
            //((Dog)new Hound()).sniff(); 
    }
}

On executing above, I get o/p as "Hound bark". So it means the cast of Dog has nothing to play any role that I can safely assume, since new Hound().bark() also gives same o/p of "Hound bark".

However, if I remove the comment from next line, i.e. ((Dog)new Hound()).sniff() and then execute program, it gives compiler error saying cannot find method sniff() in class Dog. So if in the prev syntax Dog did not play any role (as i am guessing), on what basis does it play role to invoke sniff() ?? Help. Thanks.

  1. At compile time Java checks that the method call is valid. It checks that using the declared type of the reference. You cast the reference to Dog and Dog does not have a sniff method so line 11 will be rejected by the compiler. Dog does have a bark method, so line 10 is OK.
  2. At run time the Java runtime uses the actual class of the actual object to chose which version of the method to use. The cast doesn't change the object itself, so your Hound is still a Hound, and Hound's bark method is called.

Edited 4 Years Ago by JamesCherrill

James I'm getting it a bit, but just one confusion, where is the ref var created here? It's just new Hound().... There is no LHS side of the assignment. So according to you "checks that using the declared type of the reference" where is the reference?

"reference" or "expression" - same significance in this case. An expression's returned value has a type just like a reference variable does

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