This week's book giveaway is in the General Computing forum.
We're giving away four copies of Learning Regular Expressions and have Ben Forta on-line!
See this thread for details.
Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!