Static Classes In Java

2018-12-31 18:48发布

问题:

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, that if a class contains all the static methods, shall the class be static too?

What are static classes good for?

回答1:

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 Java\'s Math class. 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.



回答2:

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.



回答3:

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(); 
  }
}


回答4:

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();


回答5:

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.



回答6:

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.



回答7:

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 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.

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



回答8:

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.



回答9:

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.