• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance Questions

 
Brian Grant
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am studying for the SCJP exam and have a couple things which have tripped me up so far on inheritance.

1. I understand that methods marked final are not inherited. But what about instance variables marked final? I'm thinking specifically about "constants" marked public static final. Are they inherited?

2. Are members marked private inherited? What I'm thinking of here is that in order to follow encapsulation best practices, I should mark my instance variables private and provide accessor methods. But if I do this, won't subclasses have to provide a whole new set of instance variables because private variables are not accessible to the subclass?

Thanks,
Brian
 
Fletcher Estes
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final methods and variables are inherited as long as they are marked public or protected. They just can't be overridden (or changed).

Nothing that is marked private is inherited, nor is visible beyond instances of the same class. If you want your subclasses to have direct access to member variables, they will need to be marked protected. Otherwise, you can always just use the public getter and setter methods, which is preferable anyway.
 
Brian Grant
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Fletcher, that helps.
 
F. Marotta
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Fletcher Estes:
final methods and variables are inherited as long as they are marked public or protected. They just can't be overridden (or changed).



IMHO:
this is correct for public, private or "default" access (included inner classes).
(obviously default access can allow inheritance only for derived classes in the same package)


am I right?


cheers
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by F. Marotta:

IMHO:
this is correct for public, private or "default" access (included inner classes).
(obviously default access can allow inheritance only for derived classes in the same package)


Actually, it is public, protected, and default members which are inherited (note that default members are only inherited by subclasses defined within the same package as the superclass). Private members are never inherited.
 
F. Marotta
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Corey McGlone:

Actually, it is public, protected, and default members which are inherited


OMG, I made a very bad typo.... yes, I meant protected when I wrote "private" (really.... )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic