What is a "static class" in Java?
Asked Answered
E

14

1158

Is there anything like static class in Java?

What is the meaning of such a class? Do all the methods of the static class need to be static too?

Is it required the other way round as well? That if a class contains only static methods, the class shall be static too?

What are static classes good for?

Endear answered 20/9, 2011 at 13:32 Comment(2)
You might be interested in https://mcmap.net/q/46821/-why-are-you-not-able-to-declare-a-class-as-static-in-javaAlisonalissa
What do you mean by “like static class”?Weigle
M
1021

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.

Mace answered 20/9, 2011 at 13:39 Comment(16)
a class Foo with only static methods is not the same as static class FooBrominate
Should the methods be final as well?Hydrosphere
@Evorlor: If a class is declared final then its methods are automatically (effectively) final. This is because a final class cannot be subclassed, and thus its methods cannot be overridden (i.e., are effectively final). docs.oracle.com/javase/tutorial/java/IandI/final.htmlHombre
Regarding the second point: As of Java 8. You don't need to make the constructor private. Hence, should you (for whatever reason) need to create an instance of the class, you still can. But with an instance of the class, you cannot access the static methodsEdva
This answer maybe addresses what the OP meant, but it (currently) does not explain Java static classes, and so does not answer the question at all! This is very bad for people who get here trying to figure out what a static class means in Java.Mcmillin
@Mcmillin if you carefully read the question and answer you' ll see that it does answer all what the initial question asksTrichromat
@JBoy: There is such a thing as "static class" in Java, which is what the question is about, but this answer does not at all explain. Instead, it explains how to simulate in Java what the answer calls a "static class" - but which is not what a "static class" in Java is! (Maybe it's what's called a "static class" in some other language(s), but people coming here to learn about Java static classes will be misled and confused.)Mcmillin
Another good use of mimicking classes is when you're writing an Automation Framework. You don't want to see the new keyword in a Test Script.Cita
I don't see why your private constructor has a body... it never gets called. Why don't you initialize the static field?Hen
does it make sense to initialize the static variable in the constructor if constructor never gets called? (it is private right?)Reckoner
What about throwing InstantiationException in the constructor's body. This prevent instantiation made by reflection?Dooley
I think the answer is not suitable for the question.Confined
you should explicitly mention that private MyStaticClass () { // private constructor myStaticMember = 1; } will have NO effect at all since the constructor will not be called. But this is not the point. I am still very confused about the utility of static inner classes in Java and their utility or added value.Sinless
@Mcmillin but it's very good for people who came here to find out about not-nested static classes ;)Greek
@Sinless The point of haviing a private constructor is preventing class clients from creating an instance of the class.Bayer
@Sinless 'Static inner' is a contradiction in terms.Vas
P
361

Well, Java has "static nested classes", but they're not at all the same as C#'s static classes, if that's where you were coming from. A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.

Static nested classes can have instance methods and static methods.

There's no such thing as a top-level static class in Java.

Psyche answered 20/9, 2011 at 13:35 Comment(10)
In Java Why does static nested class allow instance methods? What is the use of a instance method in such a class?Poundal
@Geek: Did you read my answer? Read the second sentence carefully. Why would you not want to be able to have instance methods of static classes? You can create instances of them, after all.Psyche
lets say I get the instance like this Outer.Innner nested = new Outer.Inner(). But now does it make sense to have nested.someInstanceMethod() method call from semantic point of view? This call may be legal and made permissible by the language but when I see that a class is declared static I understand that is some sort of Utility class which has just not been made top level because of packaging convenience. I would like to understand your thinking on this.Poundal
@Geek: Yes, it's entirely permissable. Your "understanding" that static classes are utility classes is incorrect, basically. That's not what static classes in Java mean at all.Psyche
then when we say that a class is static in Java, what does it say about that class? Does it say that an instance of the class can stand on its own and doesn't require help of an enclosing class instance to instantiate itself?Poundal
@Geek: Yes. Exactly as I wrote in my answer: "A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class."Psyche
@jon Skeet is outer class in java explicitly static? I found this answer and wanted to confirm #18738549Phoney
@KhurramAli: Do you mean implicitly? They're certainly not explicitly static, given that you don't use the keyword static when declaring them. They're implicitly static in that you don't need a reference to anything else in order to construct one. Personally I find the static/non-static terminology a bit odd for nested classes anyway... I think it would be simpler to talk about what the behaviour is.Psyche
@JonSkeet, if the static/non-static terminology is a bit odd for nested classes, do you think that Java would have been better off with a different keyword to declare instantiable nested classes? I am trying to understand if there is any good rationale for the re-use of the keyword static for declaring nested classes.Vaporescence
@Vaporescence Both static and non-static nested classes can be instantiated. I don't know whether a different keyword would have been better - or whether it would have been better just not to have the inner class with an implicit reference to an instance of the outer class. I don't miss it in C#.Psyche
D
190

There is a static nested class, this [static nested] class does not need an instance of the enclosing class in order to be instantiated itself.

These classes [static nested ones] can access only the static members of the enclosing class [since it does not have any reference to instances of the enclosing class...]

code sample:

public class Test { 
  class A { } 
  static class B { }
  public static void main(String[] args) { 
    /*will fail - compilation error, you need an instance of Test to instantiate A*/
    A a = new A(); 
    /*will compile successfully, not instance of Test is needed to instantiate B */
    B b = new B(); 
  }
}
Disquiet answered 20/9, 2011 at 13:35 Comment(3)
So can we say that we can uses inner static classes in order to instantiate them without the need to make them public?Sinless
@Sinless We use inner static classes in order to instantiate them from a static context (such as main). I don't think it has anything to do with visibility.Wakayama
@Sinless static/non static is orthogonal to visibility. You can have any kind of visibility with either static or non static. The point is, do you need an instance of the enclosing class, in order to create the inner one?Disquiet
G
128

Yes there is a static nested class in java. When you declare a nested class static, it automatically becomes a stand alone class which can be instantiated without having to instantiate the outer class it belongs to.

Example:

public class A
{

 public static class B
 {
 }
}

Because class B is declared static you can explicitly instantiate as:

B b = new B();

Note if class B wasn't declared static to make it stand alone, an instance object call would've looked like this:

A a= new A();
B b = a.new B();
Greenshank answered 20/9, 2011 at 13:39 Comment(1)
note that you can instantiate the un-static class regularly like B b = new B(); if you are trying to instantiate it from the Class A itself.Autograph
S
44

What's happening when a members inside a class is declared as static..? That members can be accessed without instantiating the class. Therefore making outer class(top level class) static has no meaning. Therefore it is not allowed.

But you can set inner classes as static (As it is a member of the top level class). Then that class can be accessed without instantiating the top level class. Consider the following example.

public class A {
    public static class B {

    }
}

Now, inside a different class C, class B can be accessed without making an instance of class A.

public class C {
    A.B ab = new A.B();
}

static classes can have non-static members too. Only the class gets static.

But if the static keyword is removed from class B, it cannot be accessed directly without making an instance of A.

public class C {
    A a = new A();
    A.B ab = a. new B();
}

But we cannot have static members inside a non-static inner class.

Shrink answered 18/12, 2015 at 6:5 Comment(3)
Can we instantiate a static class or does it make sense?Sadler
Not like in other languages, static has only one meaning in java. If something is static in a class that means that thing can be accessed without instantiating that class. It does not say anything regarding creating instances or not..Shrink
You can't 'set inner classes as static'. This is a contradiction in terms. A nested class is either inner or static.Vas
S
26

Can a class be static in Java ?

The answer is YES, we can have static class in java. In java, we have static instance variables as well as static methods and also static block. Classes can also be made static in Java.

In java, we can’t make Top-level (outer) class static. Only nested classes can be static.

static nested class vs non-static nested class

1) Nested static class doesn’t need a reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.

2) Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.

see here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Swain answered 10/10, 2016 at 9:19 Comment(2)
also inner 'non static' classes cannot declare static fields or methodsYetty
top level classes are static by default, that's the only reason why one cannot use the static keyword for them. It would just be redundant. (one doesn't require an instance of the class to access the class, hence they are static).Bourgogne
C
12

Seeing as this is the top result on Google for "static class java" and the best answer isn't here I figured I'd add it. I'm interpreting OP's question as concerning static classes in C#, which are known as singletons in the Java world. For those unaware, in C# the "static" keyword can be applied to a class declaration which means the resulting class can never be instantiated.

Excerpt from "Effective Java - Second Edition" by Joshua Bloch (widely considered to be one of the best Java style guides available):

As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
    INSTANCE;
    public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free , and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton. (emphasis author's)

Bloch, Joshua (2008-05-08). Effective Java (Java Series) (p. 18). Pearson Education.

I think the implementation and justification are pretty self explanatory.

Cotter answered 24/2, 2015 at 2:37 Comment(3)
A good way to implement a Singleton. Unfortunately, the question is not about Singletons, it is about static classesTheresatherese
Java has a rather unique interpretation of the "static" keyword. It looks like OP is coming from C# where "static class" is the equivalent of a singleton in Java. I've updated my answer to make this interpretation of the question clear.Cotter
A C# static class is not a Singleton. A Singleton instance is an object and can implement an interface which means it can participate in dependency injection and can be mocked. A C# static class cannot implement an interface or be injected in any way, and is much closer to just a bunch of C functions, and of course allows extension methods.Swayder
C
6

Outer classes cannot be static, but nested/inner classes can be. That basically helps you to use the nested/inner class without creating an instance of the outer class.

Cornall answered 20/9, 2011 at 13:36 Comment(2)
'Static inner' is a contradiction in terms.Vas
Outer classes are static by default (don't need an instance to create an instance)Bourgogne
F
6

In simple terms, Java supports the declaration of a class to be static only for the inner classes but not for the top level classes.

top level classes: A java project can contain more than one top level classes in each java source file, one of the classes being named after the file name. There are only three options or keywords allowed in front of the top level classes, public, abstract and final.

Inner classes: classes that are inside of a top level class are called inner classes, which is basically the concept of nested classes. Inner classes can be static. The idea making the inner classes static, is to take the advantage of instantiating the objects of inner classes without instantiating the object of the top level class. This is exactly the same way as the static methods and variables work inside of a top level class.

Hence Java Supports Static Classes at Inner Class Level (in nested classes)

And Java Does Not Support Static Classes at Top Level Classes.

I hope this gives a simpler solution to the question for basic understanding of the static classes in Java.

Fronnia answered 21/5, 2019 at 15:31 Comment(2)
'Static inner' is a contradiction in terms.Vas
top level classes are static by default (no need for an instance to access them). As they can't be non-static (you need them to create an instance), allowing the keyword static would require to denote all top-level classes as static. That's why the keyword is not supported. Doesn't mean that the property of being static is not supported.Bourgogne
P
2

You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

public class Outer {
   static class Nested_Demo {
      public void my_method() {
          System.out.println("This is my nested class");
      }
   }
public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();
      nested.my_method();
   }
}
Pernas answered 3/9, 2019 at 14:32 Comment(2)
You cannot use the static keyword with a class unless it is a nested class. 'Static inner' is a contradiction in terms.Vas
Off-topic, but your answer seems to be ripped off by these websites: Tutorialspoint, Euroinformatica, CUITutorialAvert
S
1

Is there anything like static class in java?

Singletons are 'like' a Static Class. I'm surprised no one has mentioned them yet.

public final class ClassSingleton { 

private static ClassSingleton INSTANCE;
private String info = "Initial info class";

private ClassSingleton() {        
}

public static ClassSingleton getInstance() {
    if(INSTANCE == null) {
        INSTANCE = new ClassSingleton();
    }
    
    return INSTANCE;
}

// getters and setters

public String getInfo(){
    return info;
  }
}

Usage is something like:

String infoFromSingleton = ClassSingleton.getInstance().getInfo()

Singletons are great for storing ArrayLists/List/Collection Classes/etc... If you are often gathering, updating, copying collections from multiple areas and need for these collections to be in sync. Or a Many to One.

Stooge answered 27/10, 2021 at 19:14 Comment(0)
S
-1

Java has static methods that are associated with classes (e.g. java.lang.Math has only static methods), but the class itself is not static.

Swanson answered 20/9, 2011 at 13:35 Comment(0)
V
-2

All good answers, but I did not saw a reference to java.util.Collections which uses tons of static inner class for their static factor methods. So adding the same.

Adding an example from java.util.Collections which has multiple static inner class. Inner classes are useful to group code which needs to be accessed via outer class.

/**
 * @serial include
 */
static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
                             implements Set<E>, Serializable {
    private static final long serialVersionUID = -9215047833775013803L;

    UnmodifiableSet(Set<? extends E> s)     {super(s);}
    public boolean equals(Object o) {return o == this || c.equals(o);}
    public int hashCode()           {return c.hashCode();}
}

Here is the static factor method in the java.util.Collections class

public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
    return new UnmodifiableSet<>(s);
}
Vadavaden answered 25/10, 2019 at 3:33 Comment(2)
'Static inner' is a contradiction in terms.Vas
Did not got your comment? Can you elaborate? Trying to understand your comment.Vadavaden
A
-3

A static method means that it can be accessed without creating an object of the class, unlike public:

public class MyClass {
   // Static method
   static void myStaticMethod() {
      System.out.println("Static methods can be called without creating objects");
   }

  // Public method
  public void myPublicMethod() {
      System.out.println("Public methods must be called by creating objects");
   }

  // Main method
  public static void main(String[ ] args) {
      myStaticMethod(); // Call the static method
    // myPublicMethod(); This would output an error

    MyClass myObj = new MyClass(); // Create an object of MyClass
    myObj.myPublicMethod(); // Call the public method
  }
}
Antwanantwerp answered 20/9, 2019 at 10:50 Comment(1)
Doesn't answer the question.Vas

© 2022 - 2024 — McMap. All rights reserved.