java - 错误 : cannot find symbol—Can't access another class's public field

标签 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 声明为公共(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/

相关文章:

java - 自定义线性布局未显示

javascript - 解释这个Uncaught TypeError : Property 'x' of object [object Object] is not a function

javascript - JavaScript 中的变量作用域 (Dojo)

javascript - 当 HTMLElement.onclick 事件调用时,在其函数中获取对象的属性 - javascript

C++ "Variable not declared in this scope"- 再次

java - Android,从sqlite检索数据并显示在自定义列表中的正确方法

Java继承接口(interface)中的注解

c# - 'using' 和范围界定之间的区别?

java - 是否有办法从 AsyncResttemplate 获取 http.client.requests 指标?

java - 这些代码在插入排序方面有何比较?