Originally posted by Jordi Marqu�s:
Hi!
//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() );
}
}
It will not compile. Why??
Thank you in advance.
Hello Jordi.
This is a quiet thought provoking question
Good.
Now here is my thought jordi
B will inherit all the instance
members from its Super class A. However to access those inherited
members you have to use the Subclass handler ie B b to see how the modifiers work.
If you end up using the parent handler ie A a in this case
you are acutally accessing the memeber more like a member being accessed from an interface. ie "requiring public access"
Here is the funpart jordi..
if you make small change to the existing code
say like this
//Single file B.java
class A
{
protected int i = 10;
public int getI() { return i; }
}
public class B extends 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() );
}
}
It will compile just fine
So the moral of the story is
protected access modifier works
for same package,
subclass in the samepackage
and subclass is other package
Thankyou
Ragu
[This message has been edited by Ragu Sivaraman (edited September 13, 2001).]
[This message has been edited by Ragu Sivaraman (edited September 13, 2001).]