我正在尝试找出为什么该类不能被创建为静态的?例如:
public static class Qwert {
public static void main(String args[]) {
int x = 12;
while (x<12) {
x--;
}
System.out.println(" the X value is : "+ x);
}
}
static
关键字通常用于标记一个方法或字段不是每个类实例都存在一次,而是仅存在一次。由于一个类本身只存在一次,因此所有类在这种方式上都是“静态的”,并且所有对象都是类的实例。
static
对于内部类有一个完全不同的含义:通常,内部类实例可以访问其绑定到的外部类实例的成员,但如果内部类是static
,它就没有这样的引用,并且可以在没有外部类实例的情况下实例化。也许你在某个地方看到过它,然后试图在顶级类中使用它,在那里它没有意义。static
,因此具有对外部类实例的引用。因此,默认情况下,我现在使内部类static
。) Qwert 的对象。
例如:
public class Qwert {
private Qwert() {}
public static void main(String args[]){
int x = 12;
while(x<12){
x--;
}
System.out.println(" the X value is : "+ x);
}
}
static
时,出现了modifier static not allowed here
的错误,就像这个例子一样。 - RafsQwert
的实例,您可以通过放置一个毒丸来使构造函数失败:public class Qwert {
private Qwert() throws IllegalAccessException {
throw new IllegalAccessException("Utility class!");
}
public static class Yuiop {
public Yuiop() throws IllegalAccessException {
// generates a synthetic accessor method to super()
}
}
public static void main(String args[]) {
new Yuiop();
}
}
当我们为组件使用静态关键字时,该组件变成了类级别的组件,并且其内存由其类占用。