Originally posted by Garrett:
Lets say I have a class that requires only the default constructor. I decided I wanted to block any other classes from making any calls to that constructor, so I hard coded the default constructor and made it private.
Then i thought, well if nobody can construct these objects, then their methods are useless... so I might as well make the whole class private. It said....
"modifier private not allowed here"
Assumptions
1.) To make the default constructor private, I must hard code
it and change it to private.
2.) Classes cannot be private? Ever?
Are these correct? I appreciate any input.
Just a couple of additional notes:
* Having a private constructor does not necessarily mean that no method in the class is unavailable. You can access static methods and variables without creating an instance of the class, assuming those items have appropriate permissions (e.g., they're public).
Here's an example (assume these classes are defined in separate source files):
//source file privConstructor.java
public class privConstructor
{
public static void amethod()
{
System.out.println("Ran amethod()");
}
private privConstructor(){}
}
// source file test.java
public class
test {
public static void main(
String args[])
{
privConstructor.amethod();
}
}
* an inner (or nested class) can be private or protected. A top level class can only be declared public or default (no access modifier, also known as friendly, which means accessibly within that package). For more information, you can read
http://www.jchq.net/tutorial/01_02Tut.htm