File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark ""extends" keyword and instance variables. " Watch ""extends" keyword and instance variables. " New topic

"extends" keyword and instance variables.

Nikhil Pujari

Joined: Oct 31, 2011
Posts: 21

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( But that doesn't seem to be the case. Why is this?

Einstein: A problem cannot be solved in the same state of mind in which it was created.
More motivation:
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

just paste this in your subclass and then test.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

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

Joined: Jan 05, 2012
Posts: 18
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.

I agree. Here's the link:
subject: "extends" keyword and instance variables.
It's not a secret anymore!