Java class which all its methods are static - java

What are the classes in Java which:
all its methods are static
Does not contain any instance methods

Lombok define it as UtilityClass:
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.util.Collections are well known utility classes. This annotation automatically turns the annotated class into one.
A utility class cannot be instantiated. By marking your class with #UtilityClass, lombok will automatically generate a private constructor that throws an exception, flags as error any explicit constructors you add, and marks the class final. If the class is an inner class, the class is also marked static.
All members of a utility class are automatically marked as static. Even fields and inner classes.

It sounds like you're describing a static class.
While Java does not allow you to explicitly declare a (non-nested) class as static, it is still possible to implement this paradigm.

Related

why "NestedExceptionUtils" in spring source code is declared as an abstract class?

I fount a util class in Spring named NestedExceptionUtils, and it is declared as an abstract class, why abstract? To prevent instances of it? But another class is not declared as an abstract class! Such as 'BeanDefinitionReaderUtils'. when should I do this?
NestedExceptionUtils contains a single public static method and has no derived classes (within Spring). This suggests that it's abstract to prevent instantiation.
Another and a slightly better way to create utility classes in Java is to declare a class final and define a private no-args constructor. This is better than abstract utility class because it also suppresses extending the utility class.
Spring wasn't written by a single person, this could explain why different utility classes are written in different ways.

All the classes in java belong to Object Class , then why can't a class be static

For a class being static, it is required it to be not a top level class. Since all classes belong to Object class which is the superior of all classes, then why can't we create a class with static keyword? Why is static classes allowed only in nested scenario.
All the classes in Java (transitively) extend Object, they are not inner classes inside it.
static wouldn't mean anything for top level classes, and therefore is forbidden. For inner classes, static means the same thing it means for other members (such as data members and methods) - the inner class belongs to the outer class, not to a specific instance of it.

Why is Java.Lang.Math not abstract?

The "abstract" keyword means you cannot create an instance of the class (an object).
Java.Lang.Math is preceded with the following keywords
public final class Math {
...
}
But no "abstract" keyword. The class simply provides a collection of related static variables and methods, like PI and sin().
Static means that those variables/methods can't be unique between different instances of the object (there is only one copy of those variables/methods associated with the class itself). So why even allow the programmer to create an instance of the class? Why not precede with "abstract"?
final and abstract keywords can't be applied together because final class can't be overridden and abstract classes are meant for override.
A class that is declared final cannot be subclassed that is used for creating an immutable class such as String
It's better explained under JSL section - 8.1.1. Class Modifiers
An abstract class is a class that is incomplete, or to be considered incomplete.
A class can be declared final if its definition is complete and no subclasses are desired or required.
both above statements are contradicting each-other.
If you want to read more about then have a look at Java Tutroial on A Strategy for Defining Immutable Objects
Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
Make all fields final and private.
Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects.
java.lang.Math is a Utility class (contains only static utility methods).
Correct way to define utility class is to make it final so that no other class can extend it and to have private no-args constructor so that no one can create an instance of the class.
So you won't be able to create instance of class any how. However if you go by abstract approach, you cannot use final and there is no way you can prevent it from being extended. Hence former approach is better.
If it were abstract, someone could do
public class NewMath extends Math {
which frankly speaking makes no sense.
However, you cannot create a new Math instance anyway because its only constructor is private:
private Math() {}
final means you cannot extend it, the reason you cannot create an instance is because the constructor is private. This is how (in java) you define static classes or factory classes.
The Abstract keyword means the class can't be Instantiable but it can be Extended.
And in case of Utility Classes such Math Class,Extending it has no sense. Declaring the no-args Constructor makes it Non-Instantiable and final makes it non-Extendable...So its the Perfect Match .... And If you use Abstract then you can't use Final...

Why private, static, protected access modifers are not used with a class?

and why the same, can be used with inner classes?
public class Hello {
class inner{ // this class can use any modifier
}
}
Java only allows top level classes / interfaces to be public or package.
Section 7.6 of the JLS states (Top Level Type Declarations):
By default, the top level types declared in a package are accessible
only within the compilation units of that package, but a type may be
declared to be public to grant access to the type from code in other
packages (§6.6, §8.1.1, §9.1.1).
Section 9.1.1 of the JLS of interface modifiers states:
The access modifiers protected and private pertain only to member
interfaces within a directly enclosing class or enum declaration
(§8.5.1).
The modifier static pertains only to member interfaces (§8.5.1, §9.5),
not to top level interfaces (§7.6).
I hope this is clear.
Nested classes can be static, private, protected, package-local, or public
Top level classes are not;
static as this wouldn't mean anything. static for a nest class means it doesn't hold a reference to an outer class, but if you are the outer class it doesn't have a use.
private classes cannot be access from another class file, so a private top level class couldn't be accessed.
protected classes could potentially be used from sub classes, but making the class abstract is clearer. IMHO.
Private top-level class does not make any sense because you can't access it from anywhere.
Protected means to access class within the same package or subclass of the outer class.Since there isn't package inheritance in java then protected classes also does not make any sense.
When we declare method/parameter as static, then we can access it without creating an instance of object.Because static member belongs to the class as a whole, not the instance of class or object. Since there isn't enclosing class for top-level classes, it is meaningless to define top-level classes as static.
All types of access modifiers can be used on all types of classs (except anonymous classes).
Classes with other types of modifiers, will give access, exactly like a method.
static won't work, since it means that it belongs to some other class, that is never true for an outer class.

Private constructor in abstract class

In Java what is the purpose of using private constructor in an abstract class?
In a review I got this question, and I am curious, for what situation we need to use the constructor in such way?
I think it can be used in pair with another constructor in abstract class, but this is very trivial. Also it can be used for constructing static inner classes which will excend abstract class.
Maybe there is more elegant usage?
If the private constructor is the only constructor of the class, then the reason is clear: to prevent subclassing. Some classes serve only as holders for static fields/methods and do not want to be either instantiated or subclassed. Note that the abstract modifier is in this case redundant—with or without it there would be no instantiation possible. As #JB Nizet notes below, the abstract modifier is also bad practice because it sends wrong signals to the class's clients. The class should in fact have been final.
There is another use case, quite rare though: you can have an abstract class with only private constructors that contains its own subclasses as nested classes. This idiom makes sure those nested classes are the only subclasses. In fact, enums in Java use just this idiom.
If there are other constructors around, well then there's really nothing special about the private constructor. It gets used in an abstract class just as in any other.
Only thing I can think of is reusing common code shared by the other (protected) constructors. They could then call the private constructor in their first line.
Sometimes, the default no-arg constructor is made private, and another constructor which accepts arguments is provided. This constructor might then invoke other private constructor(s) . This forces implementations to supply these arguments, which might ensure some variable is always initialized, although this is not common practice (in my experience). If this is the requirement, you would be better off checking your variables and throwing an IllegalArgumentExeption, explaining why the variable needs to be initialized.
If you create an abstract class with only private constructors, the class is practically useless as no instances can ever be created. If the intention is to create a utility class with only static methods (like the Math class in the java.lang package), private constructors are acceptable, however the class should be marked final instead, as marking the class as abstract implies the class is to be extended.
As mentioned, to be used as a common, internal-use only constructor.
Abstract or not abstract, it's not uncommon to declare a private default constructor on a class containing only static public methods [helper methods] to prevent instantiating the class.
no other elegant use is possible
A private constructor in an abstract class can also serve the purpose of sealed classes (like in Scala or Kotlin etc.). Since you can still provide subclasses from within the abstract class, but outsiders cannot extend/implement (as #Marko Topolnik answered).
It does look like we will be getting sealed interface to more cleanly support this. See https://openjdk.java.net/jeps/8222777
A final class with only private constructors is a design used by singletons and multitons.
An abstract class which has only private constructors is the only way I've seen to prevent a class from being instantiated. I have seen it used to create utility classes (which only have static methods and/or members).
As for setting up user expectations I see that https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html states "Abstract classes cannot be instantiated, but they can be subclassed." I note that it does not state any intention that they are expected to be subclassed.
I also note however that viewing some Java source code I find the following designs are used (none of which are abstract classes with only private constructors):
Final utility classes with private constructors
http://developer.classpath.org/doc/java/lang/Math-source.html
http://developer.classpath.org/doc/java/lang/System-source.html
Final utility classes with private constructors which
throw exceptions
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Objects.java
Neither abstract nor final utility classes with private constructors
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/ArrayPrefixHelpers.java
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Arrays.java
https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/FormattableFlags.java
Looks like a utility, but apparently can be instantiated (no private
constructors)
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/ArraysParallelSortHelpers.java

Categories

Resources