• Post Reply Bookmark Topic Watch Topic
  • New Topic

member data between subclass and base class  RSS feed

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question from mock exam, and the output is value is 2 value is 3;
I can't understand why the b.x=3 instead of 2, anyone explain this for me? Thanks a lot!
class Base {
int x=3;
public Base() {}
public void show() {
System.out.print(" The value is " + x);
}
}
class Derived extends Base {
int x=2;
public Derived() {}
public void show() {
System.out.print(" The value is " + x);
}
}
public class Test {
public static void main(String args[]) {
Base b = new Derived();
b.show();
System.out.println("The value is " +b.x);
}
} // end of class Test
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is simple. In a derived class methods are overridden, data members are not. So b.x does not override the derived class variable x.
 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Base b=new Derived();
b is of type base class and it is referencing to its subclass Derived, now When you call the show() by the reference variable b ,this show() method of Derived class is hiding the show() method of the Base class. so, it calls the method in the Derived class. (It applies only to methods not for varibles)
But, if you want to access the variable by the reference varibale b it directly access its own variable from the Base class.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!