• 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: 1603
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The trick is in line# 19.
 
Matthew Brown
Bartender
Posts: 4567
8
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic