• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference Types and Instance Types

 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
b.eat(a);
}
}

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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe the confusion from a lack of Code Tags...
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

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

As per your code the method is there.

Ok

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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic