public final class DateUtil{
public static void t1();
}
public abstract class DateUtil{
public static void t1();
}
abstract classes are meant to be sub-classed, and their sub-classes are meant to be instantiated, so they are not a good fit for utility classes.
If you are asking about a class that contains only static utility methods and shouldn't be instantiated, make it final and make the constructor private. That's what the JDK developers did with classes such as java.lang.Math.
Yes. Either or neither.
General opinion is that it should not be subclassable or instantiable, so add a private constructor. (Some people disagree.)
private DateUtil() {
throw new Error();
}
In general, all Util classes are final and static. It will have private constructor.
So that anyone who is calling the method ,no need to create object and can directly access with class name.
Related
When we want to close a class to inheritance we are declaring class with final,
final class Myclass {}
but when we declare the constructor private it will be the same effect,
class Myclass {
private Myclass() {}
}
But is it really the same? Is there any difference for optimization of code or readability of code? And which classes has to close to inheritance,
immutable class maybe
every method and member variable declared static of class
But for second option java.util.Arrays hasn't been declared with final even if all methods of Arrays are declared static.
but when we declare ctor private it will be the same effect
Not necessarily, consider this example using static classes:
public class SOExample {
private static class ClassWithPrivateConstructor {
private ClassWithPrivateConstructor() {
System.out.println("I have a private constructor");
}
}
private static class ClassThatExtendsClassWithPrivateConstructor extends ClassWithPrivateConstructor {
}
public static void main(String[] args) {
new ClassThatExtendsClassWithPrivateConstructor();
}
}
This will print "I have a private constructor".
but is it really same? is there any difference for optimization of code or readablity of code. and which classes has to close to inheritance,
When a developer sees that a class is final, they understand that the intention of the author was that it should not be extended.
When a developer sees that a class has a private constructor, they understand that the class can't be instantiated. This is generally because it is either a static utility class or a singleton.
But for second option java.util.Arrays hasn't declared with final even if all methods of Arrays declared static
This is a good observation. My guess is that it probably should have been but can't be changed now for backward compatibility.
What I usually do is I make the class final and the constructor private:
it removes the ambiguity about the class use (emphasising it's a utility class)
it keeps the user away from what they aren't supposed to do (to initiate, to extend).
.
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class HttpTool {}
That said, there is nothing wrong with java.util.Arrays. The designer achieves the desired effect (non-instantiability) with the necessary minimum (the private constructor).
If you want to create an immutable class or just a class that for some reason should not have childrens you should declare it as final. Private constructor should be used in utility classes, this way you block inheritance and also make sure instance of the class cannot be created.
Imagine having the classes:
public class classA {
public static String name() {
return "classA";
}
}
public class classB {
public static String name() {
return "classB";
}
}
Since both classes have the same-named static method, I would like to make something like a parent element that they would relate to that would declare that all its child would implement a static method name().
Using interfaces is impossible since I don't want the declaration of the static method to be inside the interface and static methods cannot be overridden. Also, using an abstract class is also not a solution since I can't declare an abstract static method.
Is there a way of doing what I would want to?
You can't enforce parent child relation using static keyword so no there is no way of doing this.
To be implemented by a child class, name() method should be abstract. Which isn't possible as it is static. Also study about the implications of inheriting static methods : Are static methods inherited in Java?
I'm getting this warning on Sonar:
Hide Utility Class Constructor:
Utility classes should not have a public or default constructor
My class:
public class FilePathHelper {
private static String resourcesPath;
public static String getFilePath(HttpServletRequest request) {
if(resourcesPath == null) {
String serverpath = request.getSession()
.getServletContext()
.getRealPath("");
resourcesPath = serverpath + "/WEB-INF/classes/";
}
return resourcesPath;
}
}
I want solution to remove this warning on Sonar Qube.
If this class is only a utility class, you should make the class final and define a private constructor:
public final class FilePathHelper {
private FilePathHelper() {
//not called
}
}
This prevents the default parameter-less constructor from being used elsewhere in your code.
Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.
I don't know Sonar, but I suspect it's looking for a private constructor:
private FilePathHelper() {
// No-op; won't be called
}
Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.
(You should also make the class final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)
I use an enum with no instances
public enum MyUtils {
; // no instances
// class is final and the constructor is private
public static int myUtilityMethod(int x) {
return x * x;
}
}
you can call this using
int y = MyUtils.myUtilityMethod(5); // returns 25.
Best practice is to throw an error if the class is constructed.
Example:
/**
* The Class FooUtilityService.
*/
final class FooUtilityService{
/**
* Instantiates a new FooUtilityService. Private to prevent instantiation
*/
private FooUtilityService() {
// Throw an exception if this ever *is* called
throw new AssertionError("Instantiating utility class.");
}
You can just use Lombok annotation to avoid unnecessary initialization.
Using #NoArgsConstructor with AccessLevel.PRIVATE as bellow:
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FilePathHelper {
// your code
}
I recommend just disabling this rule in Sonar, there is no real benefit of introducing a private constructor, just redundant characters in your codebase other people need to read and computer needs to store and process.
Alternative using Lombok is use #UtilityClass annotation.
#UtilityClass was introduced as an experimental feature in Lombok v1.16.2:
If a class is annotated with #UtilityClass,
the following things happen to it:
It is marked final.
If any constructors are declared in it, an error is generated.
Otherwise, a private no-args constructor is generated; it throws a UnsupportedOperationException.
All methods, inner classes, and fields in the class are marked static.
Overview:
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.
Example:
import lombok.experimental.UtilityClass;
#UtilityClass
public class FilePathHelper {
private static String resourcesPath;
public static String getFilePath(HttpServletRequest request) {
if(resourcesPath == null) {
ServletContext context = request.getSession().getServletContext();
String serverpath = context.getRealPath("");
resourcesPath = serverpath + "/WEB-INF/classes/";
}
return resourcesPath;
}
}
Reference from official documentation:
https://projectlombok.org/features/experimental/UtilityClass
Although using #UtilityClass annotation will show issue on sonarCube.
So basic problem is "Java provide a default no-argument public constructor" for a class. now we have two solutions -
Remove #UtilityClass and make it static final class with private constructor.
Instead of using it as class, Use it as Enum .
but -
When the problem in sonarQube then use -
#SuppressWarnings("java:###")
"###" rule number.
Add private constructor:
private FilePathHelper(){
super();
}
public class LmsEmpWfhUtils {
private LmsEmpWfhUtils()
{
// prevents access default paramater-less constructor
}
}
This prevents the default parameter-less constructor from being used elsewhere in your code.
SonarQube documentation recommends adding static keyword to the class declaration.
That is, change public class FilePathHelper to public static class FilePathHelper.
Alternatively you can add a private or protected constructor.
public class FilePathHelper
{
// private or protected constructor
// because all public fields and methods are static
private FilePathHelper() {
}
}
make the utility class final and add a private constructor
In Java, I can't create instances of abstract classes. So why doesn't eclipse scream about the following code?
public abstract class FooType {
private final int myvar;
public FooType() {
myvar = 1;
}
}
The code is fine, the final variable is initialized in the constructor of FooType.
You cannot instantiate FooType because of it being abstract. But if you create a non abstract subclass of FooType, the constructor will be called.
If you do not have an explicit call to super(...) in a constructor, the Java Compiler will add it automatically. Therefore it is ensured that a constructor of every class in the inheritance chain is called.
You can have constructors, methods, properties, everything in abstract classes that you can have in non-abstract classes as well. You just can't instantiate the class. So there is nothing wrong with this code.
In a deriving class you can call the constructor and set the final property:
public class Foo extends FooType
{
public Foo()
{
super(); // <-- Call constructor of FooType
}
}
if you don't specify a call to super(), it will be inserted anyway by the compiler.
You can create concrete sub-classes of FooType and they will all have a final field called myvar.
BTW: A public constructor in an abstract class is the same as a protected one as it can only be called from a sub-class.
What is your doubt?
Ok. See, an abstract class can have a constructor. It's always there-implicit or explicit. In fact when you create an object of a subclass of an abstract class, the first thing that the constructor of the subclass does is call the constructor of its abstract superclass by using super(). It is just understood, that's why you don't have to write super() explicitly unless you use parameterized constructors. Every class even if it is abstract, has an implicit constructor which you cannot see. It is called unless you create some constructor of your own. so long you created abstract classes without creating any custom constructor in it, so you didn't know about the existence of the implicit constructor.
You definitely can declare final variable in abstract class as long as you assign value to it either in the constructor or in declaration. The example that guy gave makes no sense.
No you can't declare final variables inside an Abstract class.
Check Below example.
public abstract class AbstractEx {
final int x=10;
public abstract void AbstractEx();
}
public class newClass extends AbstractEx{
public void AbstractEx(){
System.out.println("abc");
}
}
public class declareClass{
public static void main(String[] args) {
AbstractEx obj = new newClass ();
obj.AbstractEx();
// System.out.println(x);
}
}
This code runs correct and produce output as
abc
But if we remove comment symbol of
System.out.println(x);
it will produce error.
interface Int {
public void show();
}
Int t1 = new Int() {
public void show() {
System.out.println("message");
}
to.show();
You're defining an anonymous class that implements the interface Int, and immediately creating an object of type thatAnonymousClassYouJustMade.
This notation is shorthand for
Int t1 = new MyIntClass();
// Plus this class declaration added to class Test
private static class MyIntClass implements Int
public void show() {
System.out.println("message");
}
}
So in the end you're creating an instance of a concrete class, whose behavior you defined inline.
You can do this with abstract classes too, by providing implementations for all the abstract methods inline.
What this special syntax for anonymous inner classes does under the hood is create a class called Test$1. You can find that class file in your class folder next to the Test class, and if you printed t1.getClass().getName() you could also see that.
i think your object has nothing to do with the interface. If you comment out the whole interface, still you will get the same output. Its just anonymous class created. I think, unless you use the class "implements" you cant implement the interface. But i dunno how naming collision doesn't happen in your case.