为什么不能将Java类声明为static? [英] Why can't a Java class be declared as static?
问题描述
我想找到为什么类不能被创建为静态的? Like:
I am trying to find why the class cant be created as a static? Like:
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);
}
}
推荐答案
Java, static
关键字通常将方法或字段标记为对于类的每个实例不存在一次,而是一次。一个类存在一次,所以实际上,所有类都是静态这样,所有对象都是类的实例。
In Java, the static
keyword typically flags a method or field as existing not once per instance of a class, but once ever. A class exists once anyway so in effect, all classes are "static" in this way and all objects are instances of classes.
static
确实对 inner 类有一个含义,这是完全不同的:通常内部类实例可以访问它绑定的外部类实例的成员,但如果内部类
static
,它没有这样的引用,可以实例化没有外部类的实例。也许你看到那个地方,然后试图在一个顶级类中使用它,在那里没有意义。
static
does have a meaning for inner classes, which is entirely different: Usually an inner class instance can access the members of an outer class instance that it's tied to, but if the inner class is static
, it does not have such a reference and can be instantiated without an instance of the outer class. Maybe you saw that someplace, then tried to use it on a top-level class, where it isn't meaningful.
也许你在其他语言如C# ,它的语法是一个很可怕的很像Java的。
Or maybe you saw it in other languages like C#, whose syntax is an awful lot like Java's.
(有一次我不知道为什么外部类实例没有被垃圾回收 - 因为我在其他地方保持对其内部类实例的引用,内部类不是 static
,因此有一个对外部类实例的引用。因此,默认情况下,我现在做内部类 static
。
(One time I couldn't figure out why an outer class instance wasn't being garbage-collected -- it was because I was keeping a reference to one of its inner class instances elsewhere, and the inner class was not static
and so had a reference to the outer class instance. So by default, I make inner classes static
now.)
这篇关于为什么不能将Java类声明为static?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!