2

I've been asked to modify a simple class so it would not be able to be instantiated and inherited. I got confused on how to use abstract for not being instantiated and final for not being inherited.

How should I write such a class ?

Thanks in advance.

Mauricio
  • 433
  • 5
  • 15

3 Answers3

16

A class can't be both final and abstract. You can prevent instantiation by hiding the constructor, and raising an exception to prevent instantiation via reflection.

That looks like this:

final class MyClass {
    private MyClass() {
        throw new IllegalStateException("Cannot be instantiated"); //some exception
    }
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
5
// final can not be inherited
// only static methods will work on this class
final class FrozenClass {
  private FrozenClass() {
    // can not be instantiated
  }
}
cj rogers
  • 86
  • 6
4

For this reason you have to make your class final and add a private constructor: look at this example:

final class  uninstantiable {
    private uninstantiable() {
    }
}

so now whenever you try to instantiate new object it will err classname has private access in packagename.

Amir
  • 1,123
  • 8
  • 15