Hi, this is a SCJP1.5 tip from Devesh Chanchlani's site:
http://devesh2k1.googlepages.com/home The following wont compile:
package p1;
public class A {
protected int i = 10;
public int getI() { return i; }
}
package p2;
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() );
}
}
The reason given is that the variable 'i' is protected and B cannot access it. If the process method was defined as void process(B b){ b.i....etc then it will work.
My questions are:
1. Where will this error occur? On the creation of the method process (A a) or when it it called in the main method - b.process(a); ?
2. Can protected variables only be accessed in a subclass in another package using the instance of the class (i.e. B)?
3. Is Qs 2 the same for protected methods?
Thanks