aspose file tools*
The moose likes Beginning Java and the fly likes When implementing inheritance do we have to define instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When implementing inheritance do we have to define instance variables" Watch "When implementing inheritance do we have to define instance variables" New topic
Author

When implementing inheritance do we have to define instance variables

Varuna Seneviratna
Ranch Hand

Joined: Jan 15, 2007
Posts: 167
Since we make the instance variables private in order to implement Encapsulation, When implementing inheritance do we have to define even though the same, instance variables in the subclass or what is the recognized custom?


Varuna


Varuna Seneviratna
Thomas Thevis
Ranch Hand

Joined: Sep 02, 2008
Posts: 87
Hello Varuna,

as always it depends on what you're planning to do. In very rare cases you will make the variables in the super class protected instead of private and let overriding classes use them directly.
If you allow access through getters and setters, your overriding classes can use these methods. Alternatively, you could implement all state and behavior regarding those variables by an abstract class and let other classes extend the abstract class.
Another approach is to use delegation instead of inheritance. Implement the state and behavior associated with the variables by a class and let other classes use this one for state manipulation.
Re-defining the variables in overriding classes could also be a valid choice.
However, as stated before, the design choice should depend on a specific problem/task.

Hope this helps,
Thomas


SCJP 5.0, SCJD in progress
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When implementing inheritance do we have to define instance variables