有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过第二类和第三类更改类变量

我正在做一个个人项目,同时也在做实验。我有3个类包含在3个文件中:计算。java,几何学。java,以及测试。爪哇

几何学。到目前为止,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;  
    }  
}

算计。java有一个Geometry类型的公共变量和一个处理我在Geometry中创建的变量的方法。爪哇

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

最后,在测试中。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。图2和c2。图1是将数据写入内存中的相同空间,因此,当我调用c2.figure.setLength(75)时,它也改变了c1.figure.length

当我第一次写这段代码时,我假设c1.figurec2.figure会保持它们各自的值,但它们不会。有没有办法实现这一点(让c1.figurec2.figure保持它们自己的值而不改变其他值)

PS:我第一次在这里发帖,如果我把格式弄错了,我会提前道歉


共 (1) 个答案

  1. # 1 楼答案

    public static Geometry figure = new Geometry();
    

    创建一个几何体对象,而不管有多少Calculate实例。删除static关键字(每个类强制一个实例),每个Calculate对象将包含一个Geometry

    这同样适用于area成员,以及几何体对象中的lengthwidth。我认为在这种情况下,你不需要在任何地方使用静态数据(事实上,我很少在小项目中使用静态数据)

    这是值得一读的tutorial section on instance variables