Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with overriding  RSS feed

 
mathieu taziaux
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I run the 4 classes following, I don't understand why the response is 5 ant not 6...
Could you explain me please?
Thank a lot!


EDIT by mw: Added Code Tags.
[ December 29, 2006: Message edited by: marc weber ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by mathieu taziaux:
When I run the 4 classes following, I don't understand why the response is 5 ant not 6...
Could you explain me please?
Thank a lot!




Basically the question is what type of object is c1.getObject()? Since x is an instance variable, the type of the reference which is used to access it determines whether it will be the x from A or the x from B.

When you have a covariant return, a special method called a bridge method is added to the subclass.

Take a look at some of the bytecode in the subclass.



The reference type of c1 is CovariantTest so when we call the method getObject() using that reference, the overridden method is called, but it is called through the bridge method, so the reference type of the output is A.

Therefore, the instance variable associated with the class A is accessed.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

As the class names imply, this is an example of covariant return types, which is new with Java 1.5.

The true (runtime) type of c1 is SubCovariantTest, and as your println indicates, it's the overridden version of getObject in SubCovariantTest that's invoked. But the reference type of c1 is the superclass CovariantTest, and in this superclass, getObject returns a reference of type A. So when you call c1.getObject(); you get a reference to an instance of B upcast to type A. And variables (like x) are bound by reference type.

See this thread for more explanation.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!