A reference variable marked final cant reassigned to different object.The data with in object can be modified but the reference variable cannot be changed.
Based on my Understanding I have a created a code below where I am trying to reassign a new UserId of 155.As the Definition goes I am only trying to change data within the object. But the reference is same.
public class FinalClass
{
public static void main(String[] args)
{
ChildClass objChildClass = new ChildClass();
objChildClass.UserId = 155;
}
}
class ChildClass
{
public static final int UserId = 145;
}
I believe I misunderstood the above concept.
Kindly explain the same with example.
Thanks for Reply.
You can't change final value using "=" operator. If you do it, you try to change the reference (or primitive) and final
states that this cannot be changed.
You can change existing object's fields:
public static final User user = NewUser(145);
public static void main(String[] args)
{
user.setId(155);
}
Your understanding of the concept was right. Wait I will try to explain the beauty of final keyword. i have divided it in three parts :
I have written a class here hope that clarifies all the doubts you have.
public class FinalSampleTestDrive {
public static void main(String[] args) {
final FinalSample obj = new FinalSample();
FinalSample obj2 = new FinalSample();
FinalSample obj3 = new FinalSample();
obj2.setName("arya");
System.out.println(obj2.getName());
obj3 = obj2; //allowed
System.out.println(obj3.getName());
//obj = obj2 //not allowed as obj is final and can not be modified
obj.setName("shubham");
System.out.println(obj.getName());
//but the value of the instance variables, the obj is referring to
//can change
obj.setName("shivam");
System.out.println(obj.getName());
}
}
and this is the FinalSample class which is getting instantiated here :
public class FinalSample {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
You try to run it in different ways on your machine.
Happy Coding :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With