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

overriding with variables - whizlabs  RSS feed

 
Tamara Lopez
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this question from whizlabs:
============================

class A{
int x = 5;
}

class B extends A{
int x = 6;
}

public class CovariantTest{
public A getObject(){
return new A();
}

public static void main(String[] args){
CovariantTest c1=new SubCovariantTest();
System.out.println(c1.getObject().x);
}
}

class SubCovariantTest extends CovariantTest{
public B getObject(){
return new B();
}

}
====================================
I understand that variables cannot be overriden.
Here the answer is 5.
But why does c1.getObject() not return B first, and then B.x = 6??
Thanks
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe the reason is the reference type of c1.

Notice that if you change the reference type of c1 to SubCovariantTest, the output is 6.
[ April 07, 2006: Message edited by: Keith Lynn ]
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tamara,

The answer for this question is that polymorphism applies only to methods and not to variables.

The method version that will be called is defined at runtime by applying polymorphism.

On the other hand, the variable version that will be acessed (from parent or child class) is defined at compile time. So, as c1 is of type CovariantTest and getObject in this class returns an object of type A, at compile time the compiler knows that variable from A class must be accessed.

Hope that helps.
 
kotha vijaybabu
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Tamara

did u compiled ur code
it is giving error like overriding method cant return another type

see it



vijay----->scjp preparing
 
Tamara Lopez
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kotha - this will only work with 1.5 because in 1.5 when you override a method you can return a subtype of the type declared in the overriden method.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!