• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Explain the ouput

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 c = new SubCovariant();
System.out.println(c.getobject().x);
}

}

class SubCovariant extends CovariantTest{

public B getobject(){
return new B();
}

}
Answer is 5.

please explain this answer.when c.getobject() is called, at runtime ,it will select the SubCovariant class method and since it returns B's object,we should get the answer as B.x = 6 right.if i am wrong please correct me.
 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which variable is used is determined by reference type, not implementation type. This is very opposite to method invocation. When you say A a = new B(); Class A's variables will be referred even though the underlying implementation is B class. But B's methods will be invoked.

In your case, when you invoke SubCovariant.getObject(), you get B object, but it's casted to A because your reference type is the superclass. So when you call .x, you actually get A's x, not B.
[ November 14, 2006: Message edited by: James Quinton ]
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The polymorphism as you perceive it works only with methods.

When you access an instance variable through a reference then
the variable you access depends on the type of Reference you are using and not
the run time object stored int the reference variable.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic