craig
craig

Reputation: 21

Can a class be created without a default constructor?

The following class is intended to "extend" Math.random, has no object properties and so needs no default constructor, yet one exists (by default).

public class Mathematics {
    public static long random( long lower, long upper ) {
        return (    
            Math.min( lower, upper ) + 
                ((long) (
                    ( 1.0 + 
                        (double) Math.abs( upper - lower )) * 
                            Math.random() ))
        );
    }
}

Is there a way to have generic functions without having a default constructor?

Upvotes: 2

Views: 143

Answers (2)

Anubian Noob
Anubian Noob

Reputation: 13596

A private constructor to override the default one will disallow instantiation.

public class Mathematics {
    private Mathematics() { }

    // Other stuff.
}

This is vulnerable to reflection (as in you can change the accessibility), but if someone is using reflection to instantiate a class of static methods...

As posted in the comments, if you're paranoid you can even throw an exception:

private Mathematics() thows IllegalAccessError {
    throw IllegalAccessError(Mathematics.class.getName())
}

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

Give it a private no-arg constructor, and it will be just as good as not having one.

public class Foo {

   private Foo() {}

}

Upvotes: 1

Related Questions