The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference Types and Instance Types Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference Types and Instance Types" Watch "Reference Types and Instance Types" New topic

Reference Types and Instance Types

victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
class A {}
class B extends A { void eat(A a) { System.out.println("Eat A"); } }
public class C extends B
void eat(A a) { System.out.println("Eat A"); }
void eat(B b) { System.out.println("Eat B"); }
void eat(C c) { System.out.println("Eat C"); }

public static void main(String... args)
A a = new C();
B b = new C();;

The output of this code is "Eat A".
I don't understand this - I would have expected the output to be "Eat C.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
Notice in this example that the method eat(A) from B is being overridden in C. The methods eat(B) and eat(C) are overloaded versions of eat.

Since the runtime type of the object is C, but the reference type is B, the method eat(A) is called, but the overridden version of eat(A) is called.
marc weber

Joined: Aug 31, 2004
Posts: 11343

Maybe the confusion from a lack of Code Tags...

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
anil kumar
Ranch Hand

Joined: Feb 23, 2007
Posts: 447

i am new to this forum

The method in class C eat(A a) is overridden and in the same class the methods are overloaded.

In overloading case ,the compiler checks the method which has to execute at compile time.

say for example here in your code

B b=new C();

the compiler checks in B's class ,because there is a relation between B and C.If the method is not there it will give

As per your code the method is there.


And then after to that , at run time the Class C object is assigned to B.Using this you are calling the
eat method with a's reference.

That why you are getting that output.
I agree. Here's the link:
subject: Reference Types and Instance Types
It's not a secret anymore!