如何从java中的另一个类访问主类中的对象?
我有一个java语言的主类和两个子类。如何访问Y类中的xx?请帮助我,我在我的项目中需要它如何从java中的另一个类访问主类中的对象?,java,Java,我有一个java语言的主类和两个子类。如何访问Y类中的xx?请帮助我,我在我的项目中需要它 import class X,Y; public static void main(String[] args) { xx=new X; example=new Y; } public class Y{ change xx.value;//how can change it? } 如果我理解你的问题,那么你可以使用访问器和(或getter和setter,如果你愿意的话)之类的 static cl
import class X,Y;
public static void main(String[] args) {
xx=new X;
example=new Y;
}
public class Y{
change xx.value;//how can change it?
}
如果我理解你的问题,那么你可以使用访问器和(或getter和setter,如果你愿意的话)之类的
static class X {
public X(int value) {
this.value = value;
}
int value;
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public String toString() {
return Integer.toString(value);
}
}
static class Y {
public void example(X x) {
System.out.println("in example");
x.setValue(x.getValue() + 5);
}
}
public static void main(String[] args) {
X xx = new X(10);
System.out.printf("xx = %s%n", xx);
Y yy = new Y();
yy.example(xx);
System.out.printf("xx = %s%n", xx);
}
输出为
xx = 10
in example
xx = 15
使xx成为类Y的方法的参数,因为JAVA默认使用引用(对于对象),所以如果在类Y的方法中更改xx,它也将应用于方法main
import class X,Y;
public static void main(String[] args) {
xx=new X;
example=new Y;
example.modify(xx)
}
public class Y{
public void modify(X xx){ //change xx here)
}
在Y类中使用类型X参数创建一个函数,然后可以从主类调用该函数并更改xx值
import class X,Y;
public static void main(String[] args)
xx=new X;
example=new Y;
xx=example.changeXValue(xx);
}
public class Y{
public X changeXValue(X xx){
//change xx here
return xx;
}
}
我能问一下您为什么要这样做吗?你能给我们举个例子吗?