Re: Accessing private member via subclass
Michal Kleczek wrote:
But it does not have anything to do with 'i' being accessible or not. The
issue would remain if you change 'i' to public in the original example (and
it will compile fine).
I don't think we're saying the same thing. Here's the OP's example,
with one addition. This is what I'm talking about:
public abstract class Super
{
private int i;
void method(Sub s)
{
s.i = 2; // (*)
}
}
public class Sub extends Super
{
public int i; // ADDED THIS LINE!
}
Now, which "i" does C# access? In Java, the compiler forces you to
cast, which means that the "i" in Super will always be accessed. In C#,
I'm not sure. I think C# would switch from Super to Sub, which almost
certainly would introduce a bug into the code.
public class Super {
private int i;
<T extends Super> void m(T s) {
s.i = 5;
}
}
This compiles fine in Java - should it?
Because of type erasure, the code above actually executes as:
public class Super {
private int i;
void m(Super s) {
s.i = 5;
}
}
And if you deal with generics often, it's pretty obvious this is what
it's doing. <T extends Super> is a check done at compile time, not
runtime. So I don't have a problem with this. It can be confusing for
folks who are new or new to generics, I'll admit.