+ 4

[Java] I don't get new area for my program

public class Main { private int length; private int width; private int area; public Main(int l,int w){ this.length=l; this.width=w; this.area=l*w; } public void setlength(int newl){ this.length=newl; } public int getlength(){ return this.length; } public void setwidth(int neww){ this.width=neww; } public int getwidth(){ return this.width; } public int getarea(){ return this.area; } public static void main(String[] args) { Main test = new Main(1,2); System.out.println(test.getarea()); //prints the area as 2 test.setlength(5); //tried to change the length of my rectangle object System.out.println(test.getarea()); //Still prints the area as 2??????? } } I made the code above using just an online IDE. This computes the area of a rectangle. When I updated the length of my rectangle object, the area still remains the same and I don't understand why???

16th Oct 2019, 6:54 PM
J3fro C
J3fro C - avatar
4 ответов
+ 4
Why would it change? Numbers are passed by value, so it doesn't change wgen you set the length. You actually don't need an area variable, a function is enough: public int getArea() { return length * width; }
16th Oct 2019, 7:01 PM
Airree
Airree - avatar
+ 3
you should recalculate the area in setlength
16th Oct 2019, 7:01 PM
Taste
Taste - avatar
+ 2
If you want to update the area attribute every time the length or width is updated, you can do it in your setters. public void setlength(int newl){ length = newl; area = length * width; } public void setwidth(int neww){ width = neww; area = length * width; } This is, however, cumbersome and in no way better than what Airree has suggested, which is to modify your getArea() method to just return length * width.
17th Oct 2019, 2:16 AM
Hatsy Rei
Hatsy Rei - avatar
0
So to confirm, the 'area' inside my constructor only stores the initial value when an object's length and width is initialised?? I was hoping that when I do use the 'setlength()' function, the 'area' variable inside my constructor updates...... I understand the solutions you guys have said for the function 'public int getArea()' Guess I have to update the area under each setter function if there isn't any way to update the object's area within the constructor
17th Oct 2019, 12:56 PM
J3fro C
J3fro C - avatar