0

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.

4

2 回答 2

3

看起来您已将两个类都转储到当前目录(或类似目录)中。需要foo使用正确的文件名 ( A.java) 调用它们。并且您的编译器类路径(或源路径)设置为包含该目录的foo目录。

一个线索是你有两个错误信息。通常最好先对第一个进行排序,因为后续消息可能会变得奇怪。

于 2013-06-05T17:35:45.023 回答
1

您的第一个问题是编译器找不到类 A。一旦它可以找到它,它也可以找到该成员a。您的问题可能在于您运行 java 编译器的方式。我相信你是从命令行编译的,不是吗?

在这种情况下,您必须位于源根目录所在的位置。然后运行javac foo/B.java。这应该没有问题。

在您继续注意命令行选项-classpath-sourcepath. 然后我建议你开始使用 IDE。

于 2013-06-05T17:37:26.497 回答