2

I have a simple problem that I've been stuck on for some time and I can't quite find the answer to. Basically, I'm creating an object and trying to access the variables without using static variables as I was told that is the wrong way to do it. Here is some example code of the problem. I receive an error in the first class that can not be resolved to a variable. What I would like to be able to do is access t.name in other methods outside of the main, but also in other classes as well. To get around this previously I would use Test2.name and make the variable static in the Test2 class, and correct me if I'm wrong but I believe that's the wrong way to do it. Any help would be greatly appreciated =)

public class Test {
  public static void main(String[] args) {
    Test2 t = new Test2("Joe");         
  }

  public void displayName() {
    System.out.println("Name2: " + t.name);
  }
}

public class Test2 {
  String name;

  public Test2 (String nm) {
    name = nm;
  } 
}
4

5 回答 5

8

我看到其他人已经发布了代码片段,但他们实际上并没有发布为什么这些工作(在撰写本文时)。

您收到编译错误的原因是您的方法

public static void main(String[] args) {

    Test2 t = new Test2("Joe");         
}

变量 t 的作用域就是那个方法。您定义Test2 t为仅在main(String[] args)方法中,因此您只能在该方法中使用变量t。但是,如果您要将变量设置为字段,就像这样,并创建 Test 类的新实例,

public class Test {
Test2 t;
public static void main(String[] args) {
    Test test = new Test();
    test.t = new Test2("Joe");  
   test.displayName();
}

public void displayName() {
    System.out.println("Name2: " + t.name);
}
}

那么您应该不再遇到任何编译错误,因为您将变量 t 声明为在类Test范围内。

于 2012-06-23T08:51:05.173 回答
2

You may give the reference to your test object as an argument to method displayName:

public class Test {

    public static void main(String[] args) {    
        Test2 t = new Test2("Joe");         
        displayName(t);
    }

    public static void displayName(Test2 test) {
        System.out.println("Name2: " + test.name);
    }
}

Note: I also made displayName a static method. From within your main method you can only access static methods without reference.

于 2012-06-23T08:45:17.277 回答
1

将Test类修改为此

public class Test {
  private static Test2 t;

  public static void main(String[] args) {
    t = new Test2("Joe");         
  }

  public void displayName() {
    System.out.println("Name2: " + t.name);
  }
}
于 2012-06-23T08:45:55.410 回答
0

将 agetter用于您的目的。这是您的问题的一个侧面解决方案,但通常这是您应该使用getters 检索实例变量的方式。

public class Test {


public static void main(String[] args) {

    Test2 t = new Test2("Joe");         
    displayName(t);
}

public static void displayName(Test2 test) {
    System.out.println(test.getName());
}
}



public class Test2 
{
private String name;

public Test2 (String nm)
{
    name = nm;
}   

public String getName()
{
     return name;
}
}

永远记住,你的类中的变量应该是private. 这可以保护它免受类外的访问。因此,getters 是访问它们的唯一方法。和setters 或constructors 来初始化它们。

于 2012-06-23T08:48:24.830 回答
0

我认为静力学越少越好。
我将实例化 Test 并在它的实例上调用 displayName,然后将 Test2 的实例传递给 displayName。但这确实取决于总体目标是什么

于 2012-06-23T08:49:58.840 回答