• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why to create Final Class Object?  RSS feed

 
divya sharma
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am looking on my senior code he have created a "final" class and make it's object and write a comment like this :

public final class AppUtil {
// so that nobody can accidentally create an AppUtil object
private AppUtil()
{
}

/**
* formatName - formats a name string given the individual name fields
*/

Why so If it's a final class then nobody can modify it then why it's safe to create a it's object??
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A final class cannot have any subclasses. This just means that nobody can create a subclass that modifies behaviour of the final class by modifying internal data or overriding methods so they behave differently. A good example is java.lang.String; by making it final, it is ensured that String objects are and always will be immutable.

As for your example, this is a so-called utility class. It's final so nothing can subclass it, and it has only a private constructor so that no other code can instantiate it. This class most likely only contains static methods.


Actually, utility classes don't even need to be final themselves. Because there is only a private constructor and no public, protected or package visible one, subclasses cannot call super(...) because that just isn't visible. It is good practive to do so nonetheless.
 
Collins Mbianda
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on what you have in the code.

A final class is one thing and private constructor is another.

A final class means that no one can extends it. It could not have
subclasses.

From the comment of you first method(?), i guest that your class AppUtil provides utilities methods for the application.
Those methods are usely static. You don't need to call them on an instance.For that reason the constructor is private.

If there was no constructor, the compiler would have provide a default one.
Thus you can create an instance of AppUtil by new AppUtil();
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!