繁体   English   中英

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

[英]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.figurec2.figure将保持各自独立的值,但不会。 有没有办法做到这一点( c1.figurec2.figure保持自己的值而不改变其他值)?

PS:第一次在这里发布内容时,如果我弄乱了格式,我会向您道歉。

public static Geometry figure = new Geometry();

无论您有多少个Calculate实例,都将创建一个 Geometry对象。 删除static关键字(每个类强制一个实例),每个Calculate对象将包含一个Geometry

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

这是有关实例变量教程部分 ,值得一读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM