错误:无法找到符号 - 无法访问其他班级的公共字段

时间:2015-11-26 00:11:12

标签: java scope

好的,这是我的代码:

class ConnectionTest implements Connection {
    Random randomGenerator;
    public String id;

    public ConnectionTest() {
        randomGenerator = new Random();
        id = UUID.randomUUID().toString();
    }
    public boolean testConnection() {
        if (randomGenerator.nextInt(10)<3) //randomly make some false.
            return false;
        return true;
    }

}

class ConnectionFactoryTest implements ConnectionFactory {

    public Connection newConnection() {

        Connection c = new ConnectionTest();
        if (c == null)
            throw new ConnectionException("New connection failed.");
        System.out.println("New connection: " + c.id);
        return new ConnectionTest();
    }
}

编译器抱怨c没有id。我已将id声明为公开,所以不应该被其他类访问吗?

1 个答案:

答案 0 :(得分:1)

编译器在编译时检查c引用的类型:并且因为它是Connection引用(Connection类没有{{ 1}}属性),编译失败

此代码应该有效:

id

ConnectionTest c = new ConnectionTest(); 工作的一种解决方法是在连接类中定义Connection c = new ConnectionTest();成员变量。