• 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

The result of instance variable of inheritance.

 
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What's the result of the following code?

public class Question10 {

public A getObject() {
return new A();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Question10 q10 = new SubQuestion10();
System.out.println(q10.getObject()); //line 10
System.out.println(q10.getObject().x); //line 11
}

}

class SubQuestion10 extends Question10{
public B getObject() {
return new B();
}
}

class A{
int x=5;
}

class B extends A{
int x=6;
}

When I run the code, I got the result as:
B@1372a1a
5



My question is why line 11's result is not 6, but 5.
But the result of line 10 is B@1372a1a, not A@1372a1a
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sam,

Try this modified code and understand what exactly is happening...

 
reply
    Bookmark Topic Watch Topic
  • New Topic