Win a copy of Head First Android this week in the Android 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

"extends" keyword and instance variables.

 
Greenhorn
Posts: 21
Firefox Browser C++ Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


just paste this in your subclass and then test.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic