java中有静态类吗?
这样的课有什么意义。静态类的所有方法也需要是静态的吗?
是否反过来要求,如果一个类包含所有静态方法,那么这个类也应该是静态的?
静态类有什么好处?
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中有静态类吗?
单例就像一个静态类。我很惊讶居然没人提起过。
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()
单例非常适合存储数组列表/列表/集合类等…如果您经常从多个区域收集、更新、复制集合,并且需要这些集合保持同步。或者多对一。
静态方法意味着可以在不创建类对象的情况下访问它,这与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
}
}
有一个静态嵌套类,这个[静态嵌套]类不需要一个外围类的实例来实例化自己。
这些类[静态嵌套类]只能访问外围类的静态成员[因为它没有任何对外围类实例的引用…]
代码示例:
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();
}
}
除非是内部类,否则不能对类使用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();
}
}
都是很好的答案,但是我没有看到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);
}