好的,这是我的代码:
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
声明为公共(public)的,那么它不应该被其他类访问吗?
最佳答案
编译器在编译时检查c
引用的类型:因为它是一个Connection
引用(Connection
类没有 id
属性),编译失败。
这段代码应该可以工作:
ConnectionTest c = new ConnectionTest();
Connection c = new ConnectionTest();
的一个解决方法是在 Connection 类中定义 id
成员变量。
关于java - 错误 : cannot find symbol—Can't access another class's public field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33928618/