10

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Didn't the professor give you any further information to work with? Define "can not be created." – T.J. Crowder Oct 25 '16 at 08:07
  • 13
    "I am a student of BS" English might not be your first language, but you should maybe know that has quite a funny interpretation: "I am a student of bullsh*t". – Andy Turner Oct 25 '16 at 08:07
  • 1
    Constructors can throw exceptions – JonK Oct 25 '16 at 08:08
  • 1
    Do enums count as classes? `enum Foo {}`. – Andy Turner Oct 25 '16 at 08:08
  • I don't know, but just professor said: create a class whose object can not be created without using any access-modifier –  Oct 25 '16 at 11:21
  • 1
    Would creating one with a syntactic error count as cheating? :-P In a similar manner you could also have a class with a statically instantiated member of something that *itself* can't be instantiated (resulting in a compile-time error, albeit syntactically correct), or have its constructor call a nonexistent method. Please don't take this too seriously. – The Vee Oct 25 '16 at 12:10
  • Try a private default constructor – David Zimmerman Oct 25 '16 at 14:17

5 Answers5

12

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.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • I think this is the only solution that actually does it. The JLS calls enums "[a special class type](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9)" and thus they are classes. But you can't subclass them, you can't use `new` with them, and the only instances are their values. So an enum without values is a class that cannot be instantiated (other than possibly by manipulating bytecode, which I think any reasonable person can agree would be out of bounds). – T.J. Crowder Oct 25 '16 at 08:34
  • 1
    @AndyTurner Feel free to add my answer to yours as instructed by TJCrowder – nick zoum Oct 25 '16 at 08:37
  • @nickzoum: Done. :-) – T.J. Crowder Oct 25 '16 at 08:40
  • 1
    I think the throw exception in constructor is more likely the expected answer. That the instance briefly exists is an interesting side note, but not really relevant to anyone using the code. – IMSoP Oct 25 '16 at 11:39
  • Technically, enum classes can still be created using reflection – Ferrybig Oct 25 '16 at 14:44
  • @FerryBig not true. As it says in [the language spec](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9), "Reflective instantiation of enum types is prohibited.". – Andy Turner Oct 25 '16 at 16:16
6

I'm not a Java person, but other answers gave me this idea:

import java.util.*;
import java.lang.*;
import java.io.*;


class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Object o = new Problematic();

        // unreachable

    }
}

class Problematic
{
    static 
    {
        int i = 1 / 0 ;
    }
}

Try it on ideone

I'm pretty sure there's no way of making a Problematic and surviving...

(Note that when I tried throw new Exception(); in the static initializer it wouldn't compile)

AakashM
  • 62,551
  • 17
  • 151
  • 186
  • 1
    Basically a variant of the "throw Exception from Constructor" - idea, but on class-level instead of instance-level. And indeed, if you cannot initialize the class, you cannot create instances +1 – Hulk Oct 25 '16 at 12:06
  • 1
    `throw new RuntimeException();` should work in static initializers – kapex Oct 25 '16 at 13:28
  • 1
    @Kapep also gets "Main.java:20: error: initializer must be able to complete normally", the same as `Exception` – AakashM Oct 26 '16 at 07:31
  • 1
    @AakashM Nice, I didn't know that [static initializers can't just always throw or even use `return`](http://stackoverflow.com/q/13532794/897024). I just tried `if (true) throw new RuntimeException();` which works fine though, so the checks don't seem very thorough. – kapex Oct 26 '16 at 08:10
3

Have you tried the keyword abstract?

For example:

abstract class Test{}

Of course this can be overwritten, so please check this answer for a more foolproof design.

Community
  • 1
  • 1
nick zoum
  • 7,216
  • 7
  • 36
  • 80
0

Anonymous inner class should be the answer.

Example:

public abstract class HelloWorld{
    abstract void x();
    public static void main(String []args){
        System.out.println("Hello World"); 
        HelloWorld h = new HelloWorld(){
            void x(){
                System.out.println(" ");
            }
        }; 
        h.x(); 
    } 
}

A class is created, but it's name is decided by the compiler which extends the HelloWorld class and provides the implementation of the x() method.

nick zoum
  • 7,216
  • 7
  • 36
  • 80
RAHUL ROY
  • 126
  • 2
  • 13
  • 2
    To make this a useful answer, you should show some code which does this. – hyde Oct 25 '16 at 13:55
  • public abstract class HelloWorld{ abstract void x(); public static void main(String []args){ System.out.println("Hello World"); HelloWorld h=new HelloWorld(){void x(){System.out.println(" ");}}; h.x(); } } – RAHUL ROY Oct 25 '16 at 19:07
  • Here A class is created but its name is decided by the compiler which extends the HelloWorld class and provides the implementation of the x() method. – RAHUL ROY Oct 25 '16 at 19:08
0

Without hearing exactly how your professor phrased it, "without using any access-modifier" might mean they are attempting to teach you how the "default" access modifier works?

In which case:

package mypackage.nocreate;
class MyClass {
}

And then:

package mypackage;
import mypackage.nocreate.MyClass;

public class Test {
    public static void main(String[] args) {
        new MyClass();   // not allowed - in a different package
    }
}

You could argue that - in the source code at least - that doesn't use any access modifier :)

David Lavender
  • 8,021
  • 3
  • 35
  • 55
  • I think the "acces-modifer" constraint is here to prevent using a private constructor on a final class. – Asoub Oct 25 '16 at 15:03