Keith Allan Barrett (keith...@wpi.wpi.edu) wrote:
: I would expect the following program to produce an error on
: the fact that objects shouldn't have access to their super
: classes private data. It seems in this case that a object
: can gain access to its private data if it is accessed from
: another object with the same class as its super class. I am
That's right. Private and Protected restrict access by Classes not Objects.
See more below.
: new to this and would appreciate any feedback I can get.
: class Wow1 {
: private int z = 7;
: public void test() {
: Wow2 wow2 = new Wow2();
: // Why can I access and modify the private properties of my super class
: System.out.println(wow2.z);
: wow2.z = 4;
You see, the "I" in your comment in this case, the accessing object,
is _not_ "wow2". It is, in fact, the (new Wow1()) - if it had a name
it would be clearer. "NewWow1" is a Wow1, and as such does have
all access privileges to all members to all Wow1's. This is true of
C++ as well.
Now say Wow2 had a private member q. You could not access q in
Wow1.test() - but you could access it in any function of any Wow2, not
necessarily even the one which "owned" it.
Clearer now?
For a real challenge, try to figure out this one [posted in a different
thread, but really neat - credit would go to Jim Ortlieb
(o...@midway.uchicago.edu) except he just came up with the puzzle,
didn't figure out why it worked].
Since Java has such strong type casting rules,
why does the following compile?
public class bar extends Object {
double x;
public bar() {
x = 0.0;
}
}
public class foo extends Object {
int y;
foo() {
y = 1;
}
}
public class foobar extends Object {
foo f;
bar b;
public foobar() {
f = (foo)((Object)b);
}
}
George Ruban
gru...@gte.com
(One hint about the puzzle - try debugging it.
It's kind of a cheap trick :-( )