• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

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...

 
If you try to please everybody, your progress is limited by the noisiest fool. And this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic