java中有静态类吗?

这样的课有什么意义。静态类的所有方法也需要是静态的吗?

是否反过来要求,如果一个类包含所有静态方法,那么这个类也应该是静态的?

静态类有什么好处?


当前回答

是的,在java中有一个静态嵌套类。 当你声明一个嵌套类静态时,它自动成为一个独立的类,可以实例化,而不必实例化它所属的外部类。

例子:

public class A
{

 public static class B
 {
 }
}

因为类B被声明为静态的,你可以显式实例化为:

B b = new B();

注意,如果类B没有被声明为静态以使其独立,实例对象调用将看起来像这样:

A a= new A();
B b = a.new B();

其他回答

Java有静态嵌套类,但听起来像是在寻找顶级静态类。Java没有办法让顶级类成为静态的,但是你可以像这样模拟一个静态类:

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

以上建议的简单例子:

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.

鉴于这是谷歌上“静态类java”的最高结果,最好的答案不在这里,我想我应该添加它。我将OP的问题解释为c#中的静态类,这些类在Java世界中被称为单例。对于那些不知道的人,在c#中“static”关键字可以应用于类声明,这意味着生成的类永远不能被实例化。

摘自Joshua Bloch的“Effective Java - Second Edition”(被广泛认为是最好的Java风格指南之一):

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)

约书亚•布洛赫(2008-05-08)。Effective Java (Java系列)(第18页)。培生教育。

我认为实现和证明是不言自明的。

静态方法意味着可以在不创建类对象的情况下访问它,这与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
  }
}

Java有与类相关联的静态方法(例如Java .lang. math只有静态方法),但是类本身不是静态的。

都是很好的答案,但是我没有看到java.util.Collections的引用,它为它们的静态因子方法使用了大量的静态内部类。加上相同的。

从java.util.Collections中添加一个示例,其中有多个静态内部类。内部类对于需要通过外部类访问的代码进行分组非常有用。

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

下面是java.util.Collections类中的静态因子方法

public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
    return new UnmodifiableSet<>(s);
}