This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

Why there are two "a" attributes ?

 
Ranji Sura
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi... Could you please explain how there are two "a" attributes in a one object ? I think, I haven't understand this correctly.. Please help me to understand ... ?
 
Akhilesh Trivedi
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The trick is in line# 19.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Overriding only applies to methods, not instance variables. So if you declare a variable in a subclass that's got the same name as a variable in the superclass it's a separate variable. It "shadows" the original variable, which means that anywhere in your class B where you refer to a it means the a that's declared in B. But the other variable still exists, and any code in the A class will refer to that one.

If you're following good practices then this rarely causes any problems. If you make all your instance variables private then they aren't visible at all in the subclass.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic