好的,这是我的代码:
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
声明为公开,所以不应该被其他类访问吗?
答案 0 :(得分:1)
编译器在编译时检查c
引用的类型:并且因为它是Connection
引用(Connection
类没有{{ 1}}属性),编译失败。
此代码应该有效:
id
ConnectionTest c = new ConnectionTest();
工作的一种解决方法是在连接类中定义Connection c = new ConnectionTest();
成员变量。