I'm learning about the access modifiers for classes and instance variables. I know that default access modifier can be accessed within the package.
But I can't understand why this code doesn't work:
A.java :
This is the super class file with just one instance variable with default
access.
package foo;
public class A {
int a = 10;
}
B.java :
Subclass file within the same package foo
, which tries to use instance variable a
of superclass class A
package foo;
class B extends A {
public static void main(String[] args) {
B b = new B();
b.test();
}
public void test(){
System.out.println("Variable is : " + a);
}
}
This program is supposed to work, but I got cannot find symbol
error.
B.java:2: error: cannot find symbol
class B extends A {
^
symbol: class A
B.java:8: error: cannot find symbol
System.out.println("Variable is : " + a);
^
symbol: variable a
location: class B
2 errors
What is the reason for this error because as per the rule instance variable with default
access modifier can be accessed with in a package. Here, the class A
is public so it is visible to the class B
. Instance variable a
of class A
has default
access, so it can be accessed if the class A
is extended by other classes within the same package.