开发者

How to access variable in separate class

Is it possible to access a variable from a different class in the same project. If i can remember i think it is a way. I just cant remember. If anyone can help out it will be greatly appreciated. Thanks. For example if i s开发者_开发问答ave String userInfo; in one class How will i be able to access and link this information to the second class?


You could declare it in the following manner:

public static String myString = "myString"

And access it in the following manner;

TheClass.myString


If your userInfo String isn't a static field, and is instead an instance variable:

In order to access it, you'll need a reference to that instance of your class in the other class. How you go about this is really up to you, depending on the exact problem you're trying to solve.

If you're going to want access to more than that one field from the first class (let's call it A) inside more than one method of the other class then you'll likely want to save a reference to the entire instance inside your second class (let's call it B). To do that, I'd define a constructor for class B that takes an object of type A as a parameter:

public B(A a) {
     this.a = a;
}

If you only want it for one method, pass the object as a parameter of the method.

public void foo(A a) {
   // do something involving an instance of class A here
}

If you only want the one field, either pass it as a parameter for a constructor (and save it inside class B) if you'll want it in more than one method, or pass it as a parameter for the single method you need it for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜