final class AbsTest {}
class BTest extends AbsTest {}
How to prevent creation of subclass(es) without using the final keyword?
Here are the few options
Create Private Constructor
make each method final, so people can't override them. You avoid accidental calling of methods from subclass this way. This doesn't stop subclassing though.
put check into constructor for class:
if (this.getClass() != abc.class)
{
throw new RuntimeException("Subclasses not allowed");
}
But final is provided to solve such problem I must say, so better to go with final!!!
In above code how to prevent to create subclass without use of "final"
keyword
You can declare private constructors to avoid creation of Object.
private AbsTest() {
}
Related
Is it a right/recommended practice to add a private no-args constructor (which does nothing) for a class with only static utility methods and no instance variable (completely stateless)?
My reasoning for same is, i want to avoid any client using this class by instantiating it and always want this class's methods to be accessed in static fashion. Private constructor helps me adding this restriction on my utility classes.
Also i am defining my static classes as final, to avoid any client extending them; is it a right practice?
Yes.
To make sure no one instantiating it is best practice to define an private no args constructor which throw an IllegalStateException.
For example, for StringUtils class I would define the following constructor:
private StringUtils() {
throw new IllegalStateException("StringUtils class");
}
Say I have the following class:
public class FormContainer {
#EJB
private ExternalDao externalDao; // uses dependency Injection
private final OrderForm orderForm;
private final List<OrderFormContent> formContents;
public FormContainer(OrderForm orderForm) {
this.orderForm = orderForm
initializeOrderForm();
}
private void initializeOrderForm() {
formContents = externalDao.getFormContents(orderForm);
// similar for any other properties
}
// getters & setters
}
I am using this class to be able to hold all the fields that I will need to refer through the application. I am still learning good design and bad design practices so I am wondering if this bad design to initialize the properties of orderForm.
If so, how could it be improved?
It's OK.
The important rule to remember is not to allow this to "escape", which means don't let the instance be passed, directly or implicitly due to anonymous/inner classes, to another "process" (defined in the broadest terms).
The reason is that your instance may not be completely initialized when the other process gets it, which can lead to inconsistencies and weird bugs.
It's ok to call private methods from your constructor to initialize some data that used inside the class. Just be sure that your methods have no "side-effects" like long-time methods that user of your class would probably not expect with just calling your constructor.
If you have such methods, maybe you should extract Inititialize method that user of your class will use when he will be ready for it.
I've got a singleton class, which functions perfectly fine. I now just wonder what the last method is for?
public class PicassoSingleton {
private static Picasso instance;
public static Picasso with(Context context) {
if (instance == null) {
instance = new Picasso.Builder(context.getApplicationContext()).debugging(true).downloader(new ImageDownloader(context)).build();
}
return instance;
}
private PicassoSingleton() {
throw new AssertionError("No instances.");
}
}
Does anybody know what it does or what the use is?
Normally it would be enough to make the constructor private to prevent others classes from instantiating a PicassoSingleton.
Throwing an exception in the private constructor seems to be paranoid programming, because the implementor of a class knows it's internal details and must know what he does.
But there is one reason when it makes sense. Throwing an exception in the constructor will also prevent others from using reflection to instantiate an object of the class.
This will be impossible
Constructor<PicassoSingleton> constructor = PicassoSingleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance(); // will throw the AssertionError - impossible to instantiate it
It prevents the class from being instantiated, if you have no constructor specified then all classes by default can have a new instance created using new PicassoSingleton() with no arguments.
If you specify a constructor and make it private then only the class itself can create instances of itself. If you then throw an exception inside the constructor not even the class can instantiate itself and it prevents people using reflection from doing so.
Doing this essentially means that the class can provide static methods, variables, etc but can never be used as an object (unless you provide another constructor, in which case the access levels of that constructor may allow it to be used).
That's the constructor for the PicassoSingleton class. It's private to make sure you can't call it from other code. Instead, you use the with method to obtain the singleton instance of the class.
private PicassoSingleton() {
throw new AssertionError("No instances.");
}
Constructor is made private so that no new instances of the class can be created using new keyword.
PicassoSingleton is a constructor here and by making it private you are restricting other class to instantiate this.
This make the constructor unavailable to other classes and an instance of this class can only be accessed via getInstance method.
In additional to Tim B answer I want to say that, not only that you prevent this class from been used as object, you also prevent other classes to extend it.
How ever you do not have to throw exception in the constructor you can just leave it blank, the only reason to do it is protection from your self.
public static Picasso with(Context context) {
if (instance == null) {
instance = new Picasso.Builder(context.getApplicationContext()).debugging(true).downloader(new ImageDownloader(context)).build();
}
return instance;
}
this method is use to access private field "instance" and it is static bcoz then you can directly access it with its class name without making objects. and it is a public method because you may need to access it from outside of the current package. initially it is check whether instance variable is null or not. if null, then it is not already initiated. then it will create a new Object and initiate it. and finally return the instance object reference. this kind of methods are called accessior methods in programming.
private PicassoSingleton() {
throw new AssertionError("No instances.");
}
this is the constructor of the PicassoSingleton class. according to theory of Singleton design pattern definition, it should not allow to make objects of the class. to do it we can make a private constructor. private modifier is access only within the same class. So at the developing time someone mistakenly create a instance to this class it will throw a Assertion Error by telling "No Instances"
hope you get what i mean.
finally one word about class field
private static Picasso instance;
this object reference variable is to hold the object reference. and it is private to limit the access from outside of the class. and it is static reference bocz it is access from static method.
What do you think of the following way to simulate a static class in java?
You can add non static methods but you wouldn't be able to call them.
/**
* Utility class: this class contains only static methods and behaves as a static class.
*/
// ... prevent instantiation with abstract keyword
public abstract class Utilities
{
// ... prevent inheritance with private constructor
private Utilities() {}
// ... all your static methods here
public static Person convert(String foo) {...}
}
That is the usual way. However, there is not need for the abstract keyword. Using a private constructor is sufficient because
it prevents the creation of objects (from outside the class)
it prevents inheritance
The abstract keyword suggests the user that users of the class might implemented the class what is not the case here.
Item 4 in Effective Java (a very... effective book) says:
// Noninstantiable utility class
public final class Utility {
private Utility() {
throw new AssertionError();
}
}
because the explicit costructor is private:
you cannot instantiate it
you cannot extend it (as if it was declared as final)
The AssertionError isn't required but it provides another small benefit: it prevents that the costructior is accidentally invoked from within the class.
You can also create a specific annotation, like #BagOfFunction, and annotate your class:
#BagOfFunctions
public final class Utility {
private Utility() {
throw new AssertionError();
}
}
basically you trade a comment for a self-documenting annotation.
My FindBugs plugin suggests rather final class instead of abstract class. And I use that in my project. It seems to be a widespread idiom if it became a rule that is checked by FindBugs.
i would say, if you habe already a private constructor
private Utilities() {}
the abstract keyword is not neccessary. rather make it final.
the difference to your version is marginal, for any practical means.
I prefer making such classes final, but not abstract. Though it is just a matter of personal style.
By the way, I suppose it is still possible to call its instance methods if you put some energies. E.g. one can try using objenesis to create instance of class.
I'll have to agree with those above. Use "final" instead of "abstract". Remember, words like "final" and "abstract" are as much a means of communicating with your fellow programmers as they are instructions to the machine. Abstract implies that there will be descendant classes later, whereas final decidedly means that you will not, save through refactoring, see anything descended of this class (which is your intended meaning).
Further, in most standards I've seen, and consistently in my company, it is considered best practice to make the abstract class something which is specifically left unused, save as a parent of other classes. "Abstract" is treated as "blueprint" or "general structure", you would never drive an "abstract" car. On the other hand, final classes are instantiated perpetually, especially with Factory patterns.
My suggestion is: prevent incorrect use (i.e. instantiation) by placing javadocs
Isn't that simpler? I think your teammates are able to read ;)
Is there any other method of stopping inheritance of a class apart from declaring it as final or by declaring its constructor as private?
A comment
//Do not inherit please
Two more options:
make each method final, so people can't override them. You avoid accidental calling of methods from subclass this way. This doesn't stop subclassing though.
put check into constructor for class:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Then nobody will be able to instantiate subclass of your class.
(Not that I suggest using these techniques, it just came to my mind. I would use final class and/or private constructor)
Use final
Use private constructors
Use a comment:
// do not inherit
Use a javadoc comment
Make every method final, so people can't override them
Use a runtime check in the class constructor:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Final was created to solve this problem.
Make your constructors private and provide factory functions to create instances.
This can be especially helpful when you want to choose an appropriate implementation from multiple, but don't want to allow arbitrary subclassing as in
abstract class Matrix {
public static Matrix fromDoubleArray(double[][] elemens) {
if (isSparse(elements)) {
return new SparseMatrix(elements);
} else {
return new DenseMatrix(elements);
}
}
private Matrix() { ... } // Even though it's private, inner sub-classes can still use it
private static class SparseMatrix extends Matrix { ... }
}
Using final is the canonical way.
public final class FinalClass {
// Class definition
}
If you want to prevent individual methods from being overridden, you can declare them as final instead. (I'm just guessing here, as to why you would want to avoid making the whole class final.)
I'd have to say it's typically bad form. Though there are almost always cases where something is valid, I'd have to saying stopping inheritance in an OO world is normally not a good idea. Read up on the Open-Closed Principle and here. Protect your functionality but don't make it impossible for the guy who comes in and supports it...
Without using a final class, you can basically make all the constructors private:
public class A {
private A() {} //Overriding default constructor of Java
}
Which although will also make this class abstract-ish by disallowing creating an object of this class, yet as any inheritance requires super(); in the constructor, and because the constructor is private, a compilation error will be the maximum you can get when one tries to inherit that class.
Yet, I would recommend using final instead as it is less code and includes the option of creating objects.