Originally posted by Yuki Cho:
hi there,
can you please explain to me why the following code doesn't compile? i thought class B is able to access class A since B extends A even though they are in different package.
--------
//in file A.java
package p1;
public class A
{
protected int i =10;
public int getI() {return i;}
}
//in file B.java
package p2;
import p1.*;
public class B extends p1.A
{
public void process(A a)
{
a.i = a.i*2;
}
public static void main(String args[])
{
A a = new B();
B b = new B();
b.process(a);
System.out.println(a.getI());
}
}
thanks,
yuki
Hello Yuki,
The above code violates the following JLS rule:
6.6.2.1 Access to a protected Member
Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:
If the access is by a qualified name Q.Id, where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S.
Now let's read the rule from your code point of view
Let
A be the class in which a protected member
i is declared. Access is permitted only within the body of a subclass
B of
A. In addition, if
i denotes an instance field or instance method, then:
If the access is by a qualified name
a.i, where
a is an
ExpressionName, then the access is permitted if and only if the type of the expression
a is
B or a subclass of
B.
What it means is that you can use
i as long as it is not qualified by another name (i.e by itself - that means in your code, you can change a.i to i and the compiler will be happy... But that i will be the inheritted i not the i in class A). If you want to qualify
i with another name,
that name has to be of the subclass and those subclasses extended below.
Hope that helps,
- Lam -
[This message has been edited by Lam Thai (edited May 13, 2001).]