Java – create a class whose objects cannot be created
I was studying for my BS, and my professor gave me a task. He said: create a class without using any access modifiers or interface keywords that cannot create its objects
I use Google, but I can't find a solution How can this be done in Java?
Solution
Enumeration is a class that cannot be instantiated and subclassed (JLS § 8.9); Just create one without any value:
enum Foo {}
Other possibilities depend on the interpretation:
Jonk and T.J. Crowder consider throwing an exception from the constructor:
final class Example { Example() { throw new Exception(); } }
But Nick zoum points out that an instance is still created and exists, briefly, before the exception, although it cannot be retained (in the above example)
Nick zoum believes that the summary:
abstract class Example { }
... but T.J. Crowder pointed out that abstract classes can be subclassed (they cannot be final), and a subclass instance "is a" superclass instance