This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

The result of instance variable of inheritance.  RSS feed

 
Sam Sunamin
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • 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
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sam,

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

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!