Static Classes In Java
Java has static nested classes but it sounds like you're looking for a top-level static class. Java has no way of making a top-level class static but you can simulate a static class like this:
- Declare your class
final
- Prevents extension of the class since extending a static class makes no sense - Make the constructor
private
- Prevents instantiation by client code as it makes no sense to instantiate a static class - Make all the members and functions of the class
static
- Since the class cannot be instantiated no instance methods can be called or instance fields accessed - Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member
Simple example per suggestions from above:
public class TestMyStaticClass {
public static void main(String []args){
MyStaticClass.setMyStaticMember(5);
System.out.println("Static value: " + MyStaticClass.getMyStaticMember());
System.out.println("Value squared: " + MyStaticClass.squareMyStaticMember());
// MyStaticClass x = new MyStaticClass(); // results in compile time error
}
}
// A top-level Java class mimicking static class behavior
public final class MyStaticClass {
private MyStaticClass () { // private constructor
myStaticMember = 1;
}
private static int myStaticMember;
public static void setMyStaticMember(int val) {
myStaticMember = val;
}
public static int getMyStaticMember() {
return myStaticMember;
}
public static int squareMyStaticMember() {
return myStaticMember * myStaticMember;
}
}
What good are static classes? A good use of a static class is in defining one-off, utility and/or library classes where instantiation would not make sense. A great example is the Math class that contains some mathematical constants such as PI and E and simply provides mathematical calculations. Requiring instantiation in such a case would be unnecessary and confusing. See the Math
class and source code. Notice that it is final
and all of its members are static
. If Java allowed top-level classes to be declared static
then the Math class would indeed be static.
What does it mean, when we create many instances of static class?
A static class is a nested class (i.e. it is declared within another class). It behaves like a top level class, which means you can create multiple instances of it.
It doesn't have much in common with static methods or static variables.
what are the main differences between a Java/C# static class?
Static classes in Java are one of three kinds of nested classes provided by the language (the other two being non-static nested classes and function-scoped classes).
Static classes of Java behave the same way that nested classes of C#: they have access to static members of the enclosing class, but cannot access instance members without an additional reference to the enclosing object. In contrast, non-static nested functions can access instance variables, but you need an enclosing instance in order to be instantiated.
Static classes and final classes in java
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Final Classes
A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
http://docs.oracle.com/javase/tutorial/java/IandI/final.html
Concept Behind Static classes in Java
A copy paste from oracle:
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
An example:
There is no need for LinkedList.Entry or Map.Entry to be top-level class as it is only used by LinkedList aka Map. And since they do not need access to the outer class members, it makes sense for it to be static - it's a much cleaner approach.
Why are you not able to declare a class as static in Java?
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
class OuterClass {
public static class StaticNestedClass {
}
public class InnerClass {
}
public InnerClass getAnInnerClass() {
return new InnerClass();
}
//This method doesn't work
public static InnerClass getAnInnerClassStatically() {
return new InnerClass();
}
}
class OtherClass {
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
Sources :
- Oracle tutorial on nested classes
On the same topic :
- Java: Static vs non static inner class
- Java inner class and static nested class
Why there is no static class in Java
It is not a restriction, you do not need static class
to define a utility class, you only need static methods
. For example the class Math
in java is full of static methods, but the class itself is not static.
You might only need static class when you define an inner class
that you want to use without creating an instance of the enclosing class, which is allowed in Java.
You can define your utility class as follows:
class Util {
public static void method(){
// your utility method
}
}
Why can't we have static outer classes
Outer classes are already effectively static
A static
nested class means it has no reference to the outer class. An outer class already has no implicit reference to another class.
Related Topics
Image Encryption/Decryption Using Aes256 Symmetric Block Ciphers
What Does "|=" Mean? (Pipe Equal Operator)
Java 7 Language Features with Android
How to Convert a Color Integer to a Hex String in Android
How to Return an Array from Jni to Java
Error:(23, 17) Failed to Resolve: Junit:Junit:4.12
Conversion to Dalvik Format Failed: Unable to Execute Dex: Java Heap Space
Using Static Variables in Android
Java.Lang.Numberformatexception: Invalid Double: " "
Android - Programmatically Hide/Show Soft Keyboard
Differencebetween List and Arraylist
Limit Decimal Places in Android Edittext
Android Eclipse - Could Not Find *.Apk
Custom Listview Click Issue on Items in Android