Forums Register Login

Doubt About Access Modifier (Private)

+Pie Number of slices to send: Send
Hi there,
I was learning about Access Modifiers and the following doubt has risen:
The books say that a private member is not "inherited" from a superclass. But I made the following test and I got a nice surprise about this concept.
Here goes the code I used:
// My SuperClass with my
// private data member and
// getter and setter methods.
class MySuper{
private int myInt;
public void setMyInt(int i){
myInt=i;
}
public int getMyInt(){
return myInt;
}
}
//My subclass extending MySuper
class MySub extends MySuper{
}
//And a Test Class
class MyTeste{
public static void main(String[] args){
MySub m = new MySub();
m.setMyInt(9);
System.out.println("MyTeste: " + m.getMyInt());
}
}
The question is:
Once the subclass (MySub) doesn't inherit the private members from its superclass (MySuper), how come the subclass can use the getter and setter methods on a data member that it has not inherited?
Thanks in advance!
Ricardo.
+Pie Number of slices to send: Send
 


Once the subclass (MySub) doesn't inherit the private members from its superclass (MySuper), how come the subclass can use the getter and setter methods on a data member that it has not inherited?


Ah, that's the intent of encapsulation, -- hide the internals of the class, but publish the interface which can be used to access and modify the state of the object.
In your TV set, the circuit boards are private (you don't have access to them), yet when you turn up the volume using the TV interface, you modify the current through the circuit.
The entire motivation of encapsuplation is to be able to change a class implementation without affecting the code where this class is used. This is accomplished, in part, by a careful use of access modifiers. In the code sample that you posted, if member variable "myInt" was public, the users of the class would be free to reference it directly. If at some time later you decided to rename that variable in your original class, or to get rid of it altogether, you would be faced with a problem of modifying the code at a 1000 potential other spots where your class is used.
Eugene.
[ April 24, 2003: Message edited by: Eugene Kononov ]
+Pie Number of slices to send: Send
 


The books say that a private member is not "inherited" from a superclass.


I'm not totally sure that I believe that. Just because a subclass doesn't have access to private state doesn't mean that it doesn't have that state.
+Pie Number of slices to send: Send
In addition, I would like to point out that it is inaccurate to state that private components of a class are not inherited. Rather, they are inaccessable to the code.
If you had a BasicTV class with a private volume circut and public increaseVolume and decraseVolume methods, and you created a TVWithRemote subclass, your resulting object still has the volume circut, but the implementation of the Remote control methods dosen't have access to that circut, but rather uses the increaseVolume and decreaseVolume methods to adjust the volume.
+Pie Number of slices to send: Send
None the less, that is the terminology that the JLS uses to describe the situation.

The members of a class type (�8.2) are classes (�8.5, �9.5), interfaces (�8.5, �9.5), fields (�8.3, �9.3, �10.7), and methods (�8.4, �9.4). Members are either declared in the type, or inherited because they are accessible members of a superclass or superinterface which are neither private nor hidden nor overridden (�8.4.6).


and


8.2.1.3 Inheritance with private
In the example:

the class variable totalMoves can be used only within the class Point; it is not inherited by the subclass Point3d. A compile-time error occurs because method move of class Point3d tries to increment totalMoves.

 
+Pie Number of slices to send: Send
 


A compile-time error occurs because method move of class Point3d tries to increment totalMoves.


The key being compile-time. So what you are saying is, that for all instances of Point3D totalMoves does not exist? Irregardless of semantics, all state is inherited because there must be an underlying super object. Private (and perhaps package private) state is just inaccessable. In most cases even that can be obtained thru reflection.
+Pie Number of slices to send: Send
You need to look at what happens on class load.
When Point3d is created with the new function, An instance of each Object (in order) are created.
Object
Point
Point3D
Point3D now can access those Attribute and Methods in Point and Object just as if they where it's own EXCEPT private methods and variables (And package variables and methods in Object since Object is in a different package than Point or Point3D). So, while there is a copy of totalMoves in the memory space for Point, Point3D can not access it directly so, for sake of clearity, it said to "Not be Inherited". Now, x and y still exist in the memory space for Point but, since ther is no access modifier, the default access level is Package and Point and Point3D are in the Same package so, Point3D can access these directly so, they are "Inherited"
+Pie Number of slices to send: Send
 


... for sake of clearity, it said to "Not be Inherited".


Clarity aside, to say that private state is not inherited is misleading and upsets my sense of object orientation. Now it may be easy to just dismiss private state as not inherited since it is can't be accessed, but it really ain't so. The way I see it as an analogy, my father leaves a trust fund to me in his will, but I am only the administrator, the trust fund will eventually be dispersed to myself and my children. I can't touch it directly, only thru a presubscribed dispersal protocol (interface). Now did I inherit the trust fund or not? Even though I can't touch it directly, it still exists and there is a mechanism to access it.
+Pie Number of slices to send: Send
Ohhhh!!! I can't wait to watch what happens when Michael goes to James Gosling and Bill Joy and says that he does not care for the way that they phrased the Java Language Specifications .
On the other hand it might be sort of a silent one-sided conversation. :roll:
That IS the terminology that they used, therefore (at least for Java) that is what the rest of the world uses when discussing Java.
+Pie Number of slices to send: Send
So Cindy, when someone brings up an opposing point of view whether they be right or wrong, is your manner of defending your position always to insult that person instead of explain your position? All you've done is enumerated some specifications. Any moron that can read, can quote chapter and verse from the JLS. I never made any assertion that I was smarter than the likes of Gosling and Joy and hell I could be dead wrong on this but to cast insults instead of explaing to me why I'm wrong is not something that I would ever do in return.
+Pie Number of slices to send: Send
It seems that Cindy's point was that it is more a matter of semantics than of opinion, more a matter of definition than of right or wrong. And in Java, it's Gosling et al who provide the vocabulary definitions for us.
I'm sure that no offense was intended in a post so liberally laced with smileys.
- Peter
+Pie Number of slices to send: Send
 

Originally posted by Michael Morris:
but to cast insults instead of explaing to me why I'm wrong is not something that I would ever do in return.


Gee, I don't see where I insulted you, but sorry if you feel that I did.
My point was just what Peter said. The Java Language Specification DEFINES the language and the terminologies used in relation to the language. It has nothing to do with smarter. It has nothing to do with "wrong". It just that they got there first . Your post dealt with "what does the word inherit MEAN". You are simply defining it in a way different from the way that the JLS defines it. It is a nice philosophical discussion, but that's about it. And it really could confuse others - especially those working on their certifications that need to use the terminology the way the JLS does.
(Cindy wandering off to figure out where she insulted Michael . . .)
+Pie Number of slices to send: Send
 


... that it is more a matter of semantics than of opinion, more a matter of definition than of right or wrong.


That was my point in the first place. The JLS is not a text on general OO theory. When designing an OO software application it is unwise to consider the programming language. The design should be implementable in any OO language. I can see where considering private state as not inherited to be a convenience, a mind trick, but the fact is private state is inherited. If a Person class has private membersage and address and Employee subclasses Person are we then to assume by the JLS that Employee has neither age nor address? Of course not. Quoting Object Orientation by Khoshafian & Abnous:
In general, the instance variables of a class consist of the union of the instance variables of all its superclasses.
One further point, it seems a little odd to me that the subparagraph title that Cindy quoted is Inheritance with private. It would seem that on the one hand the writers are acknowledging the fact that private state is inherited but then to later make the statement that it is not inherited.
+Pie Number of slices to send: Send
 


Gee, I don't see where I insulted you, but sorry if you feel that I did.


All the smileys in the world doen't change the tone of your post. It may be a philosophical discussion, but I feel it is one of importance to anyone who may someday need to design a software system. Words and definitions do matter. They shape the way we think and reason. To say that private state is not inherited implies that private state does not affect subclasses. That is my point, notwithstanding the JLS.
+Pie Number of slices to send: Send
This is an interesting discussion!
I did a quick search on the topic "private inheritance" out on the web and this idea
occurred to me:
were the spec writers attempting to highlight
the fact that unlike C++, Java does not
allow subclasses to choose how they can access
data and methods from their parents?
a related concept - there are no "friend" classes
in Java...
This is a fundamental difference between Java and C++, but, if setting aside space for private instance variables in the superclass is not called "inheriting", then what should it be called?
After all, the mechanism that makes this happen
is still called "inheritance".
Also,I've got to admit that reading the above posts does not convince me that the spec does not
mean it this way, perhaps another interpretation
is that they meant to say: that this data
is not "publicly inherited", but then edited
out the word "public" since that is only
kind of inheritance in Java (based on the C++ meaning referred to above)..
i.e. another place where the spec is perhaps not
as clear as we would like? (the meaning of the concept is clear,
but not so the terminology?)
+Pie Number of slices to send: Send
To say that private state is not inherited implies that private state does not affect subclasses. That is my point, notwithstanding the JLS.
I agree with Michael, JLS is ambiguous on the inheritance of the private data members:
"Members of a class that are declared private are not inherited by subclasses of that class"
Although this is syntactically correct (there will be a compile error if you directly reference a private member of a super class from a subclass), it is misleading semantically, as it implies that the state of the superclass represented by its private members has nothing to do with the state of the object that extends the superclass.
Here is an example to prove to the contrary:

Output:
Derived object state:
veryPrivateInt = 10
veryPublicInt = 20
To a Java beginner, this output may indeed be very confusing, given that "Members of a class that are declared private are not inherited by subclasses of that class". This is precisely what the original poster Ricardo Santos was questioning, and it is our obligation to point out that JLS should be more clear.
How about this revision: "Members of a class that are declared private are not directly accessible by subclasses of that class"
Eugene.
[ April 25, 2003: Message edited by: Eugene Kononov ]
+Pie Number of slices to send: Send
Remember that the original question also noted that:
The books say that a private member is not "inherited" from a superclass
So I think part of the explanation should include why did the books he read say this - the answer is, the books were using the official definition of "inherited" established in the JLS. There are other definitions out there, and and it's certainly possible to use them in discussions - but it does not do a beginner any service if we simply ignore or dismiss the JLS definition, not when it's evidently the one that's been used by the books he's using.
[MM]: To say that private state is not inherited implies that private state does not affect subclasses.
[EK]: I agree with Michael, JLS is ambiguous on the inheritance of the private data members
Only if you're using a different definition of "inherited". I understand the JLS definition may not match what is used in many other sources, or what an intuitive approach might suggest - but the term is used consistently and unambiguously in the JLS. Provided we actually use the definition provided rather than inserting a different one. At least while reading the JLS, or while reading other books that use the same definition.
I mean, I could object to the JLS's use of the word "class" because it implies a group of people being taught something by an instructor, which might confuse beginners. But no, people learning Java or OO are expected to learn a new definition, not just apply the old one. Sure, the situation is much less clear-cut with "inherited" since there are other definitions in the OO community (much closer in context than the "class" example) - but the principle is the same: if a given book has taken the time to actually define an otherwise potentially ambiguous term, their definition must be considered valid while reading that book. It may seem misleading to casual readers who skipped over the book's definition and are importing a different one, but that's not the same as being "ambiguous" or "inconsistent".
[MM]: One further point, it seems a little odd to me that the subparagraph title that Cindy quoted is Inheritance with private. It would seem that on the one hand the writers are acknowledging the fact that private state is inherited but then to later make the statement that it is not inherited.
This is the only part of the JLS that I agree might actually be interpreted as self-contradictory on this topic. But as I see it, the problem is just the section title - titles are inherently shorter than the text they precede, and do not always contain the subtleties we might like. The text itself is quite clear that private members are not inherited (as per JLS definintion of course). I simply interpret the title "Inheritance with private" as shorthand for "An example of attempted inheritance with private" - the text basically reduces to "you can't do that". I agree the title is less clear than we might like, but I don't see it as actually contradicting the rest of the JLS.
Put it another way - if I write an article titled "Pink Elephants", and the article basically says "there's no such thing as a pink elephant" - did I contradict my title? I think not. The title serves to identify the topic, not as an assertion of existence. In the JLS, the title makes it easier for people wondering about the relation of the private modifier to inheritance - they go to that section, and are told clearly "no, private members are not inherited."
[EK]: How about this revision: "Members of a class that are declared private are not directly accessible by subclasses of that class"
Sounds good, as far as it goes. But unless we have the power to revise the JLS and all other books that use its definition, that won't actually help someone to understand what the JLS or other books mean when they say "inheritance".
+Pie Number of slices to send: Send
 

Originally posted by Jim Yingst:
but that's not the same as being "ambiguous" or "inconsistent".


I agree...but "misleading" is the term that I would instead use to describe the JLS's use of inheritance.
If you learn Java as your first OO language, there should be no problem with the JLS's useage of "inheritance" because you would know that this is a "coding-time" definition; i.e., it is only an issue when you are actually coding your class. I learned C++ first (and have never actually read any Java books short of the O'Reilly Nutshell books) and as such I understand inheritence as Michael does... I see the problem not how the JLS defines the term "inheritence" but rather the fact that it is a different definition than is used otherwise in the OO community.
(For the record, I did check out my copy of Stroustrup's the C++ Programming Language, and his definition is as I understood it to be; his private members are described as "not accessible," not "not inherited.")
+Pie Number of slices to send: Send
JY: Sure, the situation is much less clear-cut with "inherited" since there are other definitions in the OO community (much closer in context than the "class" example) - but the principle is the same: if a given book has taken the time to actually define an otherwise potentially ambiguous term, their definition must be considered valid while reading that book. It may seem misleading to casual readers who skipped over the book's definition and are importing a different one, but that's not the same as being "ambiguous" or "inconsistent".
Your point well taken, Jim. All I am saying is that it may be inappropriate to answer a Java beginner question by pointing him to that "Private Inheritance" section in JLS without explaining what definition of "inheritance" is used.

JM: (For the record, I did check out my copy of Stroustrup's the C++ Programming Language, and his definition is as I understood it to be; his private members are described as "not accessible," not "not inherited.")
That's what I am talking about. Stroustrup gets my nomination for the next revision of JLS. I hear he is still alive in those C++ usenet groups.
[ April 25, 2003: Message edited by: Eugene Kononov ]
Tongue wrestling. It's not what you think. And here, take this tiny ad. You'll need it.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1280 times.
Similar Threads
Overriding and Overloading
try/catch with exception casting
what is output of below code and why??
Doesn't an Inner Class constructor propagate upwards by adding super() ?
Inheritance of Superclass Members
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 04:50:21.