如何从实例创建者之外的另一个类访问方法

时间:2018-02-08 21:41:14

标签: java

我创建了3个java文件:main.java,GUI.java,Serial.java

在Main中,我创建了两个最后的java文件的实例。 我可以从Main中调用gui和serial的方法。 我不能从Main之外的实例gui和serial调用方法。

package main;
 public class Main {

        public static void main(String[] args) {
            GUI gui = new GUI();
            gui.setVisible(true);

            Serial serial = new Serial();
            serial.getPorts();
            fillList();
        }

        public void fillList () {
            gui.setList("hoi");
        }
    }

这是为什么?如何从方法fillList中调用gui中的方法? 感谢您的任何见解。

1 个答案:

答案 0 :(得分:2)

实例仅存在于它们声明的方法中,在本例中是构造函数。解决此问题的常用方法是在类中声明field,并在构造函数(或其他方法)中指定该字段的值。尝试:

package main;
public class Main {
    // private GUI gui; // replaced this line with the below. See comment 5
    private static GUI gui; // this is the new field declaration

    public static void main(String[] args) {
        gui = new GUI(); // note I removed the class declaration here since it was declared above.
        gui.setVisible(true);

        Serial serial = new Serial();
        serial.getPorts();
        fillList();
    }

    public void fillList () {
        gui.setList("hoi"); // now this method has access to the gui field 
    }
}
相关问题