• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

overriding with variables - whizlabs  RSS feed

 
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
 
Ranch Hand
Posts: 2410
  • 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 ]
 
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.
 
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!