0
Why does the NUMBER variable still change although i declared it as final?
public class add { private final int NUMBER; //any constant variables should be in CAPS public add(int x){ NUMBER = x; } } public class Final { public static void main(String[] args) { add addingTen = new add(10); add addingEleven = new add(11); System.out.println(addingTen); System.out.println(addingEleven); System.out.println(addingTen); } } OUTPUT : sum = 10 sum = 11 sum = 10
3 ответов
+ 4
Actually you are not changing final variable you just created three objects of class add so all the members will be encapsulate in all three objects so every object has its own final variable and you are assingning value to those by passing value to arguments.
Mark final variable and method as static then you wont be able to change the value because static members are independent of each object and shared by every objects.
+ 1
it's very simple
you actually
assign the value from using x variable
if assign values directly to NUMBER variable it cont change the value
but u use a x variable so if x value change automatically final variable changed
+ 1
use static with final variable so you won't be able to change it again