Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the use of creating object as a final?.  RSS feed

 
sujitha reddy
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
what is the difference b/w final objects and normal objects.

public class A
{
........
.........
.........

}

final A a=new A();
A b=new B();

what is difference b/w a & b;


Thanks and Regards
Madhu
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Other than the fact that A and B are different classes?

A "final" variable is one that cannot be changed after being initialized. Note that this means the object that the variable refers to can't be changed, but the object's member variables may themselves be changed.

Please don't post stuff like this in the "Advanced" forum. Moving to Java in General (Beginner.)
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final A a=new A();
A b=new B();

You can assign a value to a final variable once. That is the difference. After you last line of code you could say b = a but you'll get a compiler error if you try a = b.

Because a is already initialized. Therefore you declare a variable as final when you would like to avoid programming errors like replacing the value of a variable with another.

The final keyword, when apply to an object variable will not avoid, however, that the state of a mutable object is changed.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice that there is no such thing as a final *object*. What is final in your example is the *reference* to the object, not the object itself (which is an important distinction).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!