java中有静态类吗?
这样的课有什么意义。静态类的所有方法也需要是静态的吗?
是否反过来要求,如果一个类包含所有静态方法,那么这个类也应该是静态的?
静态类有什么好处?
java中有静态类吗?
这样的课有什么意义。静态类的所有方法也需要是静态的吗?
是否反过来要求,如果一个类包含所有静态方法,那么这个类也应该是静态的?
静态类有什么好处?
当前回答
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()
单例非常适合存储数组列表/列表/集合类等…如果您经常从多个区域收集、更新、复制集合,并且需要这些集合保持同步。或者多对一。
其他回答
好吧,Java有“静态嵌套类”,但它们与c#的静态类完全不一样,如果你是从那里来的的话。静态嵌套类只是一个没有隐式引用外部类实例的类。
静态嵌套类可以有实例方法和静态方法。
在Java中没有顶级静态类这种东西。
有一个静态嵌套类,这个[静态嵌套]类不需要一个外围类的实例来实例化自己。
这些类[静态嵌套类]只能访问外围类的静态成员[因为它没有任何对外围类实例的引用…]
代码示例:
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();
}
}
鉴于这是谷歌上“静态类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页)。培生教育。
我认为实现和证明是不言自明的。
Java中的类可以是静态的吗?
答案是肯定的,我们可以在java中有静态类。在java中,我们有静态实例变量、静态方法和静态块。在Java中,类也可以是静态的。
在java中,我们不能使顶级(外部)类是静态的。只有嵌套类可以是静态的。
静态嵌套类vs非静态嵌套类
1)嵌套静态类不需要外部类的引用,但是 非静态嵌套类或内部类需要外部类 参考。
2)内部类(或非静态嵌套类)既可以访问静态 和Outer类的非静态成员。静态类不能访问Outer类的非静态成员。它只能访问静态 外层阶级的成员。
请看这里:https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Java有与类相关联的静态方法(例如Java .lang. math只有静态方法),但是类本身不是静态的。