什么是“静态类”?在Java中?

发布于 2024-12-05 15:55:10 字数 1700 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

滴情不沾 2024-12-12 15:55:10

Java 有静态嵌套类,但听起来您正在寻找顶级静态类。 Java 无法使顶级类静态,但您可以像这样模拟静态类:

  • 声明您的类 final - 防止扩展该类,因为扩展静态类没有意义
  • 使构造函数private - 防止客户端代码实例化,因为实例化静态类是没有意义的
  • 使所有类的成员和函数static - 由于该类无法实例化,无法调用实例方法或访问的实例字段
  • 请注意,编译器不会阻止您声明实例(非静态)成员。仅当您尝试调用实例成员时,该问题才会出现

根据上面建议的简单示例:

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

静态类有什么好处? 静态类的一个很好的用途是定义一次性的、实用的和/或实例化没有意义的库类。一个很好的例子是 Math 类,它包含一些数学常量,例如 PI 和 E,并且仅提供数学计算。在这种情况下要求实例化是不必要的并且会造成混乱。请参阅 Math 类和 源代码< /a>.请注意,它是final,并且它的所有成员都是static。如果 Java 允许将顶级类声明为静态,那么 Math 类确实是静态的。

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.

混浊又暗下来 2024-12-12 15:55:10

嗯,Java 有“静态嵌套类”,但它们与 C# 的静态类完全不同(如果您来自 C#)。静态嵌套类只是一种不隐式引用外部类实例的类。

静态嵌套类可以具有实例方法和静态方法。

Java 中不存在顶级静态类这样的东西。

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.

圈圈圆圆圈圈 2024-12-12 15:55:10

有一个静态嵌套类,这个[静态嵌套]类不需要封闭类的实例即可实例化自身。

这些类[静态嵌套类]只能访问封闭类的静态成员[因为它没有对封闭类的实例的任何引用...]

代码示例:

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

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(); 
  }
}
吹泡泡o 2024-12-12 15:55:10

是的,java中有一个静态嵌套类。
当您将嵌套类声明为静态时,它会自动成为一个独立的类,可以实例化该类,而无需实例化它所属的外部类。

示例:

public class A
{

 public static class B
 {
 }
}

由于 class B 被声明为静态,因此您可以显式实例化为:

B b = new B();

请注意,如果 class B 未声明为静态以使其独立,实例对象调用将如下所示:

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

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();
情独悲 2024-12-12 15:55:10

class 内的成员声明为 static 时会发生什么?无需实例化类即可访问这些成员。因此,使外部类(顶级类)static没有任何意义。因此这是不允许的。

但是您可以将内部类设置为静态(因为它是顶级类的成员)。然后可以访问该类,而无需实例化顶级类。考虑以下示例。

public class A {
    public static class B {

    }
}

现在,在不同的类 C 中,可以访问类 B,而无需创建类 A 的实例。

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

静态类也可以有非静态成员。只有类变得静态。

但是,如果从类 B 中删除 static 关键字,则在不创建 A 实例的情况下无法直接访问它。

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

但是我们不能在非静态内部类中拥有static成员。

What happens when members inside a class are declared as static? Those 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.

鹿港巷口少年归 2024-12-12 15:55:10

Java中的类可以是静态的吗?

答案是可以,我们可以在Java中拥有静态类。在java中,我们有静态实例变量以及静态方法静态块。 Java 中的类也可以设为静态。

在java中,我们不能将顶级(外部)类设为静态。 只有嵌套类可以是静态的。

静态嵌套类与非静态嵌套类

1)嵌套静态类不需要外部类的引用,但是
非静态嵌套类或内部类需要外部类
参考。

2)内部类(或非静态嵌套类)可以访问静态
和外部类的非静态成员。静态类不能访问外部类的非静态成员。它只能访问静态
外层阶级的成员。

请参阅此处: https://docs.oracle.com/javase/tutorial/ java/javaOO/nested.html

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

迷雾森÷林ヴ 2024-12-12 15:55:10

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

摘自 Joshua Bloch 的《Effective Java - 第二版》(被广泛认为是最好的 Java 风格指南之一):

从 1.5 版开始,有第三种方法来实现单例。只需使用一个元素创建一个枚举类型:

// 枚举单例 - 首选方法
公共枚举猫王{
    实例;
    公共无效离开建筑物(){...}
}

这种方法在功能上与公共字段方法等效,只是它更简洁,免费提供序列化机制,并提供针对多重实例化的铁定保证,即使面对复杂的序列化或反射攻击也是如此。虽然这种方法尚未被广泛采用,但单元素枚举类型是实现单例的最佳方式。(强调作者的)

Bloch, Joshua (2008-05-08)。有效的 Java(Java 系列)(第 18 页)。培生教育。

我认为实施和理由是非常不言自明的。

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.

憧憬巴黎街头的黎明 2024-12-12 15:55:10

外部类不能是静态的,但嵌套/内部类可以是静态的。这基本上可以帮助您使用嵌套/内部类,而无需创建外部类的实例。

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.

轮廓§ 2024-12-12 15:55:10

简单来说,Java 仅支持内部类将类声明为静态,而不支持顶级类。

顶级类一个java项目在每个java源文件中可以包含多个顶级类,其中一个类以文件名命名。顶级类前面只允许使用三个选项或关键字:public、abstract 和 Final

内部类:顶级类内部的类称为内部类,这基本上是嵌套类的概念。 内部类可以是静态的。使内部类静态的想法是利用实例化内部类的对象而不实例化顶级类的对象。这与静态方法和变量在顶级类中的工作方式完全相同。

因此Java支持内部类级别的静态类(在嵌套类中)

并且Java不支持顶级类的静态类。

我希望这能为这个问题提供一个更简单的解决方案对 Java 中的静态类有基本的了解。

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.

梦里人 2024-12-12 15:55:10

除非它是内部类,否则不能对类使用 static 关键字。静态内部类是一个嵌套类,它是外部类的静态成员。可以使用其他静态成员来访问它,而无需实例化外部类。就像静态成员一样,静态嵌套类无法访问外部类的实例变量和方法。

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

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();
   }
}
少跟Wǒ拽 2024-12-12 15:55:10

java中有类似静态类的东西吗?

单例“就像”静态类。我很惊讶还没有人提到过它们。

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

用法类似于:

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

单例非常适合存储 ArrayLists/List/Collection Classes/等等...如果您经常从多个区域收集、更新、复制集合并且需要这些集合同步。或多对一。

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.

亚希 2024-12-12 15:55:10

静态类是属于类本身而不是类的任何特定实例的类。它用于将相关方法或常量分组在一起,并且不需要创建实例来访问其成员。静态类通常用于实用函数或组织代码。

需要记住的一些要点:

  • 静态类始终是嵌套类
  • 只能访问外部类的静态成员。
  • 外部类不能是静态的。
  • 过度使用静态类可能会导致代码紧密耦合,从而更难以维护和测试

A static class is a class that belongs to the class itself rather than to any particular instance of the class. It's used for grouping related methods or constants together, and it doesn't require an instance to be created to access its members. Static classes are often used for utility functions or for organizing code.

Some points to remember:

  • Static classes are always nested classes
  • Access only static members of the Outer class.
  • Outer class can not be static.
  • Overusing static classes can lead to tightly coupled code, which can be harder to maintain and test
你丑哭了我 2024-12-12 15:55:10

我的答案将与上面的答案类似,尽管我的答案可能更清晰并且有更清晰的示例。

通过说你希望类是静态的,你是说你基本上只需要该类的一个实例存在,因此我们可以在类本身中创建该类的实例变量,我实际上只看到它与用于返回硬编码或默认值的对象。

您基本上是在类本身内创建类的静态实例。这是根据被调用的类自动构造的,并且由于 INSTANCE 是静态的,因此该类只有一个实例。这有效地使您的顶级 Java 类静态化。

这是一个示例:

public class A {
    private static final A INSTANCE = new A();

    public static A getInstance() {
        return INSTANCE;
    }
}

然后您可以将所有其他方法添加到该类中。这会导致该类仅存在一个实例。在这种情况下,您不使用构造函数。

My answer is going to be similar to an answer above, although mine may be more clear and with a much more clear example.

By saying you want the class to be static, you are saying that you basically only need one instance of that class to ever exist, therefore we can create an instance variable of that class within the class itself, I have really only seen this used with objects that are used to return hardcoded or default values.

You basically create a static instance of the class within the class itself. This is automatically constructed upon the class being called, and because the INSTANCE is static, there is only one instance of the class. The effectively makes your top-level Java class static.

Here is an example:

public class A {
    private static final A INSTANCE = new A();

    public static A getInstance() {
        return INSTANCE;
    }
}

Then you can add all of your other methods to that class. This results in only one instance of this class existing. In this scenario, you do not use a constructor.

风月客 2024-12-12 15:55:10

Java 具有与类关联的静态方法(例如 java.lang.Math 仅具有静态方法),但类本身不是静态的。

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.

过期以后 2024-12-12 15:55:10

所有好的答案,但我没有看到对 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);
}

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);
}
老子叫无熙 2024-12-12 15:55:10

静态方法意味着无需创建类的对象即可访问它,这与 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
  }
}

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
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文