Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"extends" keyword and instance variables.

 
Nikhil Pujari
Greenhorn
Posts: 21
C++ Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is about overriding and instance variables. Now I know instance variables cannot be overridden, but I can't get this. I found this in the Rules Roundup game.



I thought the System.out.println(name) is replaced within the Test class as System.out.println(this.name). But that doesn't seem to be the case. Why is this?
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


just paste this in your subclass and then test.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you call printname() on an object of the Test class, it's calling the printname() method in Exam (Test inherits it from there).
But the line System.out.println(name) in Exam can only refer to the name variable in Exam, because the Exam class knows nothing about the Test class.

The important thing to remember is that overriding applies to methods, but not instance variables. Which name variable is used is decided at compile time.
 
raju salla
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
You are calling method, not instance variable of the super class. when you are calling the method of the super class it will get executed as it is. As per the method you have defined in super class it is printing the variable, but not you are calling the variable directly.

thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic