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

[534 byte] By [Karotijama] at [2007-10-2 5:36:55]
# 1
The field i is accessible to the subclass but a.i is not accessible because the instance is not directly derived.IMHO, use protected only when it is really needed. 99% of my fields are private or public.
Peter-Lawreya at 2007-7-16 1:47:26 > top of Java-index,Java Essentials,Java Programming...
# 2
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 !!!!!!!!!!!!!!
Karotijama at 2007-7-16 1:47:26 > top of Java-index,Java Essentials,Java Programming...
# 3

> 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.

targaryena at 2007-7-16 1:47:26 > top of Java-index,Java Essentials,Java Programming...
# 4

> 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.

warnerjaa at 2007-7-16 1:47:26 > top of Java-index,Java Essentials,Java Programming...
# 5
Yeah,,, rite.. The subclass can only see the protected member and cannot access it through the parent class reference.Thanks !
Karotijama at 2007-7-16 1:47:26 > top of Java-index,Java Essentials,Java Programming...