Is there any other method of stopping inheritance of a class apart from declaring it as final or by declaring its constructor as private?
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...
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)
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.)
- 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"); }
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 { ... }
}