Note that there are some explanatory texts on larger screens.

plurals
  1. POChanging class variables by means of a second and third class
    primarykey
    data
    text
    <p>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.</p> <p>Geometry.java so far only contains some variables I want to work with, the get/set methods along with a constructor method.</p> <pre><code>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; } } </code></pre> <p>Calculate.java has a public variable of type Geometry and a method to work with the variables I created in Geometry.java.</p> <pre><code>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; } } </code></pre> <p>Finally, in Test.java I'm creating a variable c1 of type Calculate.</p> <pre><code>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()); } } </code></pre> <p>The console output is: "L1: 75 L2: 75"</p> <p>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 <code>c2.figure.setLength(75)</code> it also altered <code>c1.figure.length</code>.</p> <p>When I first wrote this code I assumed <code>c1.figure</code> and <code>c2.figure</code> would maintain their own separate values but they don't. Is there a way to achieve this (have <code>c1.figure</code> and <code>c2.figure</code> maintain their own values without altering the other)?</p> <p>PS: First time I post here, I apologize in advance if I messed up the formatting.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload