Results 1 to 4 of 4
- 04-20-2010, 01:23 AM #1
Member
- Join Date
- Mar 2009
- Posts
- 45
- Rep Power
- 0
Inheritance - accessing private variables
Hi, im really a beginner at java but just trying to understand some basic inheritance theory.
I understand how to make a subclass and make a constructor in the subclass but what i'm confused with is accessing the superclass' private variables.
For example say a subclass has a method which calculates its private variable with a private variable from its superclass. I'm pretty sure:
(superclasses variable)*(subclass variable)
will produce an error with how the superclass variable is private.
I read that getter methods are used to access private variables values from a superclass. I'm just wondering in the subclass' method, how is this done to use these getter methods to get the value I(from superclass private variable) and make the calculation?
Any explainations or examples are much appreciated. I've looked on the net for examples but there either not related to what i'm after or just way to in depth with information which isn't where my java knowledge is yet ^.^Last edited by counterfox; 04-20-2010 at 01:31 AM.
- 04-20-2010, 02:28 AM #2
Senior Member
- Join Date
- Mar 2010
- Posts
- 266
- Rep Power
- 4
Java Code:class SuperClass { private int x; protected int y; // getter public int getX () { return x; } } class SubClass extends SuperClass { private int z; public int calculateStuff () { return z * y * getX (); } }
- 04-20-2010, 09:58 AM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Even better, simply provide an accessor to the private variable, whether protected or public...and final in both cases. "final" because you will almost never want a subclass to be able to overwrite that logic.
The general rule (and as with all general rules, there will be exceptions) is attributes should be inaccessible except via accessors.
- 04-26-2010, 01:21 AM #4
Member
- Join Date
- Mar 2009
- Posts
- 45
- Rep Power
- 0
Similar Threads
-
OOP Question re. private variables and extending classes
By ImplicitCharm in forum New To JavaReplies: 7Last Post: 07-28-2009, 03:46 PM -
accessing variables
By emp in forum New To JavaReplies: 3Last Post: 04-23-2009, 04:36 AM -
Private or Protected access for super class variables
By Madushan in forum New To JavaReplies: 3Last Post: 03-14-2009, 07:22 AM -
[SOLVED] Accessing private constructor
By piyu.sha in forum New To JavaReplies: 2Last Post: 10-06-2008, 05:45 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks