Jarod Jarod - 5 months ago 11
Java Question

Java calling object in method outside of main

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;
}
}

Answer

I see others have posted code snippets, but they haven't actually posted why any of this works (at the time of this writing.)

The reason you are getting a compilation error, is that in your method

public static void main(String[] args) {

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

Variable t's scope is just that method. You are defining Test2 t to only be in the main(String[] args) method, so you can only use the variable t in that method. However, if you were to make the variable a field, like so, and create a new instance of the Test class,

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);
}
}

Then you should no longer be getting any compilation errors, since you are declaring the variable t to be in the class Test scope.