Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 另一个类中的变量访问_Java_Oop - Fatal编程技术网

Java 另一个类中的变量访问

Java 另一个类中的变量访问,java,oop,Java,Oop,我在x类中有一个变量,我还有一个叫做“Y”的类来访问这个变量。如果值在Y类中递增,它会改变X类中的值吗 假设您将其定义为 public int anInteger = 4; 那么是的,它会改变 这些都是从实验中学到的最好的东西,尝试各种方法来构造类、声明变量和访问它。看看会发生什么。是的。您只需将对它的引用传递给另一个类。Java使用按值传递,但我们可以通过将对象作为参数传递给如下方法来实现您的要求: public class ClassX { public int classId; pu

我在x类中有一个变量,我还有一个叫做“Y”的类来访问这个变量。如果值在Y类中递增,它会改变X类中的值吗

假设您将其定义为

public int anInteger = 4;
那么是的,它会改变


这些都是从实验中学到的最好的东西,尝试各种方法来构造类、声明变量和访问它。看看会发生什么。

是的。您只需将对它的引用传递给另一个类。

Java使用按值传递,但我们可以通过将对象作为参数传递给如下方法来实现您的要求:

public class ClassX {

public int classId;

public ClassX(int id) {
    this.classId = id;
}

public void setId(int id) {
    classId = id;
}

public int getId() {
    return classId;
}
}


public class ClassY {
public static void main(String[] args) {
    ClassX cx = new ClassX(100);
    ClassY cy = new ClassY();

    System.out.println("classId:"+cx.classId);
    cy.modifyId(cx); // an object is passed as argument to a method
    System.out.println("classId:"+cx.classId);

}

public void modifyId(ClassX classx) {
    classx.setId(220);
}
}

你好我们能看看你的代码吗?如何实现
x
Y
类?这取决于如何增加类
x
中的值。它是私有的并且由getter返回,那么可能是否,您是否直接访问它,因为它在类
Y
的visibily范围内,那么是的。