• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Object References..help me....

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is repeat question..but I am not able to get it.. My understanding is written in comments..
class B
{
int i=1;
String test()
{
return "base";
}
}
class D extends B
{
int i=2;
String test()
{
return "derived";
}
public static void main(String arg[])
{
B b=new B();
// In above line , a new object of type B is created in garbage collected heap. A cup of name b is created with a remote control which refences to above object created on heap.
D d=new D();
// In above line , a new object of type D is created in garbage collected heap. A cup of name d is created with a remote control which refences to above object created on heap.
B bd=new D();
// In above line , a new object of type D is created in garbage collected heap. A cup of name bd is created with a remote control which refences to above object created on heap.
System.out.println(b.i); //should prints 1
System.out.println(d.i); //should prints 2
System.out.println(bd.i); //should prints 2 ( Iam not getting it!!..Why it is printing 1 instead of 2 .
System.out.println(b.test());
System.out.println(d.test());
System.out.println(bd.test());
}
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Member variables are statically bound, as are static methods. This means that when there is more than one version of the variable / method in the class hierarchy, the compiler will choose which one to execute at compile time based on the declared type of the reference used to access the variable or method. (Unlike dynamic binding for non-static methods, where the JVM decides at run time, based on the actual type of the object that the reference refers to.)
In this case, reference bd is declared as type B, even though the actual object it referes to is type D. Since it is declared as B, bd.i accesses the i defined in class B. Which of course equals 1, and that's what's printed.
reply
    Bookmark Topic Watch Topic
  • New Topic