Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

**Inheritance and member variable question**

 
wonkty wang
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi People, I got the following question from the mock exam...



The answer is that "easy" will get printed. I just dont understand it why.
As after inheritance, the subclass SCJPExam has it own copy of difficultyLevel, isn't?? Can anyone please explain here?

Thanks
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
inheritance and polymorphism.


Here you got confused with polymorphism.

behavior(only instance-methods) can be over-ridden.

FOR state(memebers either static or non-static) , THERE IS NO POLYMORPHISM concept like overloading or over-riding.


in your example:
Move following to Child class and test it;

public void printDifficultyLevel(){
}
System.out.println(difficultyLevel);

}
 
wonkty wang
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

Yeah, I know only the member method (not the member variable)could be overridden. However,the subclass does get a copy of member variable from the super class by inheritance. I guess my question would be:

when get runs. why it access the superclass member variable "difficultyLevel" instead of the subclass ones.

Thanks.
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now in you are in real soup.

A method in parent class(***not-over-ridden-in-child), How you can expect to access the state of child ?

*** Remember if you instantiate Child --> parent also gets instantiated.
 
wonkty wang
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help. I think I got the whole basic concept wrong. Inheritance is the logic concept which means there is not a physically a copy of whatever member variable or member methods. I guess the subclass just has the access to the superclass's methods or variables.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic