[英]Changing class variables by means of a second and third class
我正在做一个个人项目,并同时进行实验。 我在3个文件中包含3个类:Calculate.java,Geometry.java和Test.java。
到目前为止,Geometry.java仅包含我要使用的一些变量,get / set方法以及构造函数方法。
package project;
public class Geometry {
public static double length, width;
public Geometry() {
this.setLength(20);
this.setWidth(30);
}
public void setLength(double length){
this.length = length;
}
public void setWidth(double width){
this.width = width;
}
public double getLength(){
return this.length;
}
public double getWidth(){
return this.width;
}
}
Calculate.java具有类型为Geometry的公共变量,以及使用我在Geometry.java中创建的变量的方法。
package project;
import project.Geometry;
public class Calculate {
public static Geometry figure = new Geometry();
public static double area;
public void calcArea(){
this.area = figure.getLength() * figure.getWidth();
}
public double getArea(){
return this.area;
}
}
最后,在Test.java中,我将创建一个Calculate类型的变量c1。
package project;
import project.Calculate;
public class Test{
public static void main(String[] args){
Calculate c1 = new Calculate;
Calculate c2 = new Calculate;
c1.figure.setLength(55);
c2.figure.setLength(75);
System.out.println("L1: "+c1.figure.getLength()+" L2: "+c2.figure.getLength());
}
}
控制台输出为:“ L1:75 L2:75”
我对输出的解释是c1.figure和c2.figure将数据写入内存中的同一空间,因此,当我调用c2.figure.setLength(75)
它也更改了c1.figure.length
。
当我第一次编写此代码时,我假设c1.figure
和c2.figure
将保持各自独立的值,但不会。 有没有办法做到这一点( c1.figure
和c2.figure
保持自己的值而不改变其他值)?
PS:第一次在这里发布内容时,如果我弄乱了格式,我会向您道歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.