Access modifier problem... please help
//file A.java
package p1;
public class A{
protected int i = 10;
public int getI(){
return i;
}}
// 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() );
}}
This code fails to compile ..Its unable to access i.
Why is it? Please help
> But Class A is public and i variable is protected,$
> that means i can be accessed in a class within the
> package and also by any subclass of A.
> So why the error? I did not quite get it
> !!!!!!!!!!!!!!
I don't know how to explain that, but your approach is wrong anyway. public void process(A a) {
a.i = a.i * 2;
}
You shouldn't have one A take another A as an arg to process it. The A should just process itself. (And I know this is a B, but all Bs are As).
public void process() {
i *= 2;
}
This will probably work as far as the protected member goes too.
Also, since you're importing p1.*, you can just say extends A instead of extends p1.A.
> But Class A is public and i variable is protected,
> that means i can be accessed in a class within the
> package and also by any subclass of A.
> So why the error? I did not quite get it
> !!!!!!!!!!!!!!
B can access its own 'i' member (or 'this.i', maybe even referenced as 'super.i'). That's not what you're doing. You're trying to access the 'i' member of another object instance.
Yeah,,, rite.. The subclass can only see the protected member and cannot access it through the parent class reference.Thanks !