Create a Class whose object can not be created

user3847788 :

I am studying for my BS, and my professor has given me a task, he said: Create a class without using any access modifier or interface keyword whose object can't be created.

I went through Google but can't find the solution. How can this be done in Java?

Andy Turner :

Enums are classes (JLS§8.9) that cannot be instantiated and cannot be subclassed; just create one without any values:

enum Foo {}

Other possibilities depending on interpretation:

JonK and T.J. Crowder considered throwing an exception from the constructor:

final class Example {
    Example() {
        throw new Exception();
    }
}

But nick zoum pointed out that an instance is still created and exists, briefly, prior to the exception, even though it cannot (in the example above) be retained.

nick zoum considered abstract:

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=455658&siteId=1