Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this warning about utility classes in Java

Tags:

java

I'm learning Java and OOPS and while programming a basic Hello World in eclipse, I see a yellow triangle telling me 'utility classes should not have a public or default constructor'. I'm not able to understand why exactly is this happening and what does it mean? What am I doing not right?

class HelloWorld {   public static void main(String[] args) {     // TODO Auto-generated method stub             System.out.println("Hola Mundo!");  }     } 

EDIT1: Edited the code to include changes suggested.

final class HelloWorld {   private HelloWorld() {     throw new AssertionError("Instantiating utility class...");  } public static void main(String[] args) {     // TODO Auto-generated method stub             System.out.println("Hola Mundo!");  }   } 

Still getting the alert on the line Class HelloWorld.

Edit2:

Created a new class and now it works. Thanks Jon.Why does the old class still give warning? Bohemian I'm still not aware about the concepts mentioned by you in your post. I would come back to them once I get a better idea. Thank you for explaining things.

like image 529
gizgok Avatar asked Oct 14 '11 10:10

gizgok


People also ask

What are utility classes in java?

A utility class is a class that is just a namespace for functions. No instances of it can exist, and all its members are static. For example, java. lang. Math and java.

Why do we use utility class in java?

utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static (see Static variable) scope. Examples of utility classes include java.

What is utility class programming?

What is Utility Class? Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated. It contains a bunch of related methods, so they can be reused across the application.

Should utility classes be static java?

Pure utility classes should usually be static. When you have a class with well-defined input and output, no side effects and no state, then by definition it should be a static class.


2 Answers

It means that someone can write:

HelloWorld helloWorld = new HelloWorld(); 

when you probably don't want them to - you're not providing any instance members, so why allow them to create instances? Rewrite your code as:

final class HelloWorld {      private HelloWorld() {         // Prevent instantiation         // Optional: throw an exception e.g. AssertionError         // if this ever *is* called     }      public static void main(String[] args) {         System.out.println("Hola Mundo!");     } } 
like image 174
Jon Skeet Avatar answered Sep 20 '22 12:09

Jon Skeet


What Jon said, but you should know too that every class has a constructor, whether you declare one or not. If you do not declare one, then the "default constructor" is implicitly defined for you.

In other words, these two classes are identical in behaviour:

public class ClassA { }   public class ClassB {     public ClassB() {     } } 

BEWARE: Having a private constructor does not prevent instantiation!

And just to be anal, having a private constructor does not prevent someone from instantiating your class, it just makes it harder:

There are (at least) two ways to get around it:

Declare a factory method (obvious, but if it's your company's code, someone can do this):

public class ClassA {     private ClassA() {}      public static ClassA create() {         return new ClassA(); // oops! this one got away     } } 

Use reflection (sneaky, and seems wrong somehow, but it works!):
public class ClassA {     private ClassA() {} }  // Elsewhere, in another class across town: Constructor<?> constructor = ClassA.class.getDeclaredConstructor(); // constructor private? no problem... just make it not private! constructor.setAccessible(true); // muhahahaha Object obj = constructor.newInstance(); System.out.println(obj.getClass().getSimpleName());  // Prints ClassA! 

The only way to guarantee no one creates an instance is to throw an exception in a (might as well make it private) constructor:

public class ClassA {     private ClassA() {         throw new UnsupportedOperationException();     } } 
like image 40
Bohemian Avatar answered Sep 23 '22 12:09

Bohemian