I'm working on a personal project and at the same time experimenting with it. I've got 3 classes contained in 3 files: Calculate.java, Geometry.java, and Test.java.
Geometry.java so far only contains some variables I want to work with, the get/set methods along with a constructor method.
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 has a public variable of type Geometry and a method to work with the variables I created in 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;
}
}
Finally, in Test.java I'm creating a variable c1 of type Calculate.
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());
}
}
The console output is: "L1: 75 L2: 75"
My interpretation of the output is that c1.figure and c2.figure are writing data to the same space in memory and thus, when I called c2.figure.setLength(75)
it also altered c1.figure.length
.
When I first wrote this code I assumed c1.figure
and c2.figure
would maintain their own separate values but they don't. Is there a way to achieve this (have c1.figure
and c2.figure
maintain their own values without altering the other)?
PS: First time I post here, I apologize in advance if I messed up the formatting.