Should a class with only static methods be abstract? - java

I have a class that offers a collection of static utility-type methods.
On the one hand, I don't want the class to be able to be instantiated. On the other hand, I don't want to send the signal that the class should be inherited from (not that I think that it's likely).
Should this class be abstract or not?

make the class final and make the default constructor private and do not provide any public constructors. that way no one can subclass it or create an instance of it.

Don't declare it abstract; declare a private constructor, so no one, not even a subclass, can instantiate an instance of your utility class.
You can declare your class final, although if all constructors are private, then no one will be able to subclass it anyway.
To borrow the idea from Pshemo's comment in another answer, throw a RuntimeException in the constructor to prevent reflection's setAccessible method in AccessibleObject from allowing instantiation:
public class MyUtility
{
private MyUtility()
{
throw new RuntimeException("Instantiation of MyUtility is not allowed!");
}
public static void utilityMethod()
{
// Your utility method here.
}
}

Although a top-level class can't be declared static, you can make the class non-instantiable (and practically 'static') to other classes by declaring the default constructor private, which forbids instantiation because no constructor is visible.

Another version of #mre's answer
enum MyClass{
;//this semicolon indicates that this enum will have no instances
//now you can put your methods
public static void myMethod(){
//...
}
}
Enum by default is final and its constructor is private. Also you cant create its instance with reflection because it checks in Constructor#newInstance if you are trying to instantiate Enum object.

What is contained in a class has no bearing on whether it should be abstract. The key take away: an abstract class must have another class extending it (a 'concrete' class); only that concrete class can be instantiated.
To prevent it from being extended, use final.
To prevent it from being instantiated, make the constructor private.
Observe that in Java these are discrete concepts.

No, it is a utility class.
It should be final with a private default constuctor, to avoid instantiation.
If you have checkstyle enabled you would get a warning if you dont do it.

Seriously, you don't have to do anything. Nothing bad will happen, nobody is going to instantiate/subclass your class.

In addition to all the other calls to give the class a private constructor, you should also make it final so that it is clear nothing can subclass it.
public final class Utils
{
// prevent accidental construction.
private Utils()
{
}
public static void foo()
{
//util code here
}
}

Related

Why is the need of Protected constructor in Abstract class in java

While reviewing the java code, I have seen that the constructor of an abstract class is made protected.
public abstract class A {
protected A() {
}
}
What
Abstract means to me is that you can't create the instance of this
class and use this class after extending
.
And protected constructor also ensures that.
What is the point of doing two things, one making constructor protected and second making the class abstract for solving the same purpose.
Making the constructor protected doesn't prevent other classes from the same package or other classes that extend this class from instantiating the class using this constructor. Therefore the abstract keyword is required to prevent instantiating.
You can declare the constructor of an abstract class as public, but you still won't be able to instantiate this class, so it's pointless. On the other hand, a private constructor will not be usable by sub-classes of your abstract class (only be other constructors of the abstract class itself). Hence, any constructor of the abstract class that should be available to all sub-classes of the abstract class should be protected.
Of course, in your particular example there's no need to declare the constructor at all, since it has an empty body and there are no other constructors. This means the compiler will generate a parameter-less constructor with an empty body anyway.
It's true that reducing the visibility of the constructor in an abstract class (from public to protected) changes nothing regarding the inability of code to directly instantiate the abstract class.
However, that is not the point. One makes the constructor protected just to control scopes, in the same way one makes member properties private.
Here's a modified version of the same class showing that the point is not to prevent instantiation:
public abstract class A {
protected A() {
this(0);
}
private A(int a) {
// not accessible to anyone but members of A
// the point is not to prevent instantiation, but to restrict access
}
}
If making the constructor protected were meant to prevent instantiation, then one could argue that instantiation would be possible within the abstract class itself or its subclasses.

Constructor of a class

I am having trouble understanding this.
"Lastly, modify WordTransformer and SentenceTransformer so you can not create an instance of the class. Remember, with static methods and variables, you do not need to make an instance of a class. (Hint: a constructor of a class is what allows an instance of that class to be created...new WordTransformer(), what keyword can you add to the definition of that constructor that will prevent the construct from being called anywhere but in the class itself?)"
It says so you can not create an instance of this class, but if you make the class private it becomes an error. Says the only options are public static or final.
well you shall qualify the constructor as private, not the class. cf this document:
Private constructors prevent a class from being explicitly instantiated by its callers.
here's an example:
public class WordTransformer {
private WordTransformer() {
}
}
N.B.: as it sounds a lot like an assignment, I hope that you'll read the linked documentation and understand why and when to use it!
Make the constructor private:
private WordTransformer(){}
private WordTransformer(...) {
...
}
Making the constructor private will allow other methods of this class to create instances of the class but no one can create instances from the outside. Example of when this is used in practice is the singleton pattern or builder pattern.
Private constructor and static methods on a class marked as final.

System class in Java

I'm learning Java and as I know only abstract classes and interfaces cannot be instantiated. However documentation of java.lang.System says that it cannot be instantiated which is neither abstract nor an interface.
I haven't got any explanation of it. Can somebody please explain this ?
Moreover Can somebody create such classes ?
It's simple: It have no public Constructor.
You can do that yourself:
final public class Abc {
private Abc() {}
}
java.lang.System is java's version of a "static" class, meaning a class with only static methods and which does not require, or allow, an instance to be created before being used.
Since java doesn't allow the keyword "static" for class definitions (like C#), the best way to achieve such a static class is to make it's constructor private. For instance:
public final class System {
private System() { throw new UnsupportedOperationException(); }
public static void method1() { ... }
...other public static methods
}
This isn't fool proof, ie. checked by the compiler, but would restrict the class to only be created from within one of it's own methods, which the programmer is expected to know not to do (and will be reminded so by the exception if they should forget).
To instantiate a class you need a visible constructor. java.lang.System doesn't provide one, though.
Easy: Make a class final, so it can't be extended and let it have a private constructor, so a new System() won't work.
That's how System works.
You cannot instantiate a class which doesn't have public constructor, juste create a class with a private constructor and make it final so no other class can extend it :
public final class MyClass {
private MyClass() {
}
}
Note that you'll either need a public static member which will instantiate an object of the class for you (c.f. the Singleton pattern), or only static members.

Java final abstract class

I have a quite simple question:
I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...
This class should neither be instantiated, nor being extended. That made me write:
final abstract class MyClass {
static void myMethod() {
...
}
... // More private methods and fields...
}
(though I knew, it is forbidden).
I also know, that I can make this class solely final and override the standard constructor while making it private.
But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...
And I hate workarounds. So just for my own interest: Is there another, better way?
You can't get much simpler than using an enum with no instances.
public enum MyLib {;
public static void myHelperMethod() { }
}
This class is final, with explicitly no instances and a private constructor.
This is detected by the compiler rather than as a runtime error. (unlike throwing an exception)
Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"
public final class MyClass { //final not required but clearly states intention
//private default constructor ==> can't be instantiated
//side effect: class is final because it can't be subclassed:
//super() can't be called from subclasses
private MyClass() {
throw new AssertionError()
}
//...
public static void doSomething() {}
}
No, what you should do is create a private empty constructor that throws an exception in it's body. Java is an Object-Oriented language and a class that is never to be instantiated is itself a work-around! :)
final class MyLib{
private MyLib(){
throw new IllegalStateException( "Do not instantiate this class." );
}
// static methods go here
}
No, abstract classes are meant to be extended. Use private constructor, it is not a workaround - it is the way to do it!
Declare the constructor of the class to be private. That ensure noninstantiability and prevents subclassing.
The suggestions of assylias (all Java versions) and Peter Lawrey (>= Java5) are the standard way to go in this case.
However I'd like to bring to your attention that preventing a extension of a static utility class is a very final decision that may come to haunt you later, when you find that you have related functionality in a different project and you'd in fact want to extend it.
I suggest the following:
public abstract MyClass {
protected MyClass() {
}
abstract void noInstancesPlease();
void myMethod() {
...
}
... // More private methods and fields...
}
This goes against established practice since it allows extension of the class when needed, it still prevents accidental instantiation (you can't even create an anonymous subclass instance without getting a very clear compiler error).
It always pisses me that the JDK's utility classes (eg. java.util.Arrays) were in fact made final. If you want to have you own Arrays class with methods for lets say comparison, you can't, you have to make a separate class. This will distribute functionality that (IMO) belongs together and should be available through one class. That leaves you either with wildly distributed utility methods, or you'd have to duplicate every one of the methods to your own class.
I recommend to never make such utility classes final. The advantages do not outweight the disadvantages in my opinion.
You can't mark a class as both abstract and final. They have nearly opposite
meanings. An abstract class must be subclassed, whereas a final class must not be
subclassed. If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.
This is very simple explanation in plain English.An abstract class cannot be instantiated and can only be extended.A final class cannot be extended.Now if you create an abstract class as a final class, how do you think you're gonna ever use that class, and what is,in reality, the rationale to put yourself in such a trap in the first place?
Check this Reference Site..
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.
Thanks..

Are there good reasons for a public constructor of an abstract class

It is not possible to create an object by directly calling the constructor of an abstract class. The constructor of an abstract class can be called only from a derived class. It therefore seems to me that constructors of an abstract class must be either protected or package-private (the latter for the unusual cases of restricting use of a constructor to derived classes within the package). Yet Java allows the constructor of an abstract class to be public.
Are there any circumstances in which it is useful to declare the constructor of an abstract class to be public, rather than protected or package-private?
This is not quite a duplicate of the question "Abstract class constructor access modifier": clearly you can declare a constructor to be public; I want to know whether there is ever any good reason to do so. It seems to me that there is not. I see that C# has a similar peculiarity.
The answer is the same for java:
THere's no reason for a public constructor for an abstract class. I'd assume that the reason that the compiler doesn't complain is as simple that they just didn't spend time covering that since it really doesn't matter if it's public or protected. (source)
You can't call a constructor of an abstract class from anything other than a direct subclass.
So adding a special rule for access modifiers of constructors of abstract classes wouldn't add something useful to the language.
One thing that looks like an exception from this rule - if the abstract class only defines a default constructor, then the subclass does not have to implement a constructor: this is legal:
public abstract class A {
public A() {}
}
public class B extends A {}
So we can create a B by calling new B() - but note, that we still create a B and not an A. And, again, it doesn't matter if the constructor in A is public or protected. It just shouldn't be private, but the compiler will notice and complain...
Actually we invoke an "invisible" public default constructor on B which does a simple super() call...
The visibility also infuences what is shown in the javadoc (if it's selected to exclude certain visibility levels). As it doesn't matter otherwise, that could be a usage for a public constructor of an abstract class.
If you provide no constructor, then the default constructor is public if the class is public. Easiest option would be to allow that, rather than forcing protected constructors.
In that sense the reverse question may make it clear: why didn't they force protected constructors in abstract classes? Because public constructors won't change anything, so it would just take time and add complexity.
Call me a heretic, but ... I see at least one use for a constructor in an abstract class.
That is: to specify what the constructor parameters look like.
Specify an abstract constructor (thus making the class abstract). Derived classes have to implement this constructor with its specific signature to lose abstract status.
I see no other way to specify mandatory constructor signatures (help me out if you do).
You can have a public constructor if you do not define in a constructor in the sub-class.
example
abstract class Animal {
String name;
public void Animal(String name) {
this.name = name;
}
}
class Cat extends Animal{
public String sayMayName() {
return this.name;
}
}
myCat = new Cat("tester");
name = myCat.sayMyName();
if no constructor is defined the parent class constructor will be called, if it is not public it will not work. This I think is more elegantly done with a factory pattern, but I used it in practice in PHP and it works fine.

Categories