0
import javax.swing.*;

class Person {
     public String name;

     public static void main(String[] args) {
         new Person().enter();
     }
     void enter(){
        Person a = new Person();
        String first = JOptionPane.showInputDialog(null,"Enter your first name");
        a.name = first;
        new la().a();
     }
}
class la{
     void a(){
        Person a = new Person();
        System.out.println(a.name);
    }
}

As you can see what I'm trying to do here is to set global var 'name' from the JOption input and to then be able to access 'name' with the new inputted var, from other classes later on. Since the workings of the classes later on depend on that var 'name'. Now I know I can simply pass these on through constructors to the relevant classes and avert this problem, but I want to know if this way is possible at all ?

4

2 回答 2

0

现在,通过不指定您的类是公共的,您将其设置为默认值。默认为包私有,因此其他包中的类将无法访问此类的公共变量。

将类声明为 Public 并将任何全局变量设置为 Public,它们将是可访问的。

于 2012-08-17T15:01:25.720 回答
0

你的榜样不会达到你想要达到的目标。

您在 中创建一个新实例PersonMain为其分配一个新实例,然后创建一个 的新实例la,这将创建它自己的实例Person

这些不同的实例之间没有联盟。

public static void main(String args[]) {
    String first = JOptionPane.showInputDialog(null,"Enter your first name");
    // You should be checking the return result, but any way...
    Person person = new Person();
    person.name = first;

    La la = new La(person);

}

public class La {
    public La(Person person) {
        System.out.println(person.name);
    }
}
于 2012-08-17T15:04:57.223 回答