Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Static Class?

I have a class full of utility functions. Instantiating an instance of it makes no semantic sense, but I still want to call its methods. What is the best way to deal with this? Static class? Abstract?

like image 812
Nick Heiner Avatar asked Dec 04 '09 01:12

Nick Heiner


People also ask

What is static class in Java?

You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members.

What is a static class?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

When should we use static class in Java?

In Java, the static keyword is primarily used for memory management. We can use the static keyword with variables, methods, blocks, and classes. Using the static class is a way of grouping classes together. It is also used to access the primitive member of the enclosing class through the object reference.

How do you create a static class?

Make the constructor private - Prevents instantiation by client code as it makes no sense to instantiate a static class. Make all the members and functions of the class static - Since the class cannot be instantiated no instance methods can be called or instance fields accessed.


Video Answer


1 Answers

Private constructor and static methods on a class marked as final.

like image 52
David Robles Avatar answered Sep 19 '22 17:09

David Robles