• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

member data between subclass and base class

 
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 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic