[英]Static Class Non-Static Member
I'm reading a book on android game development and I've come across the first patch of code: 我正在阅读一本有关Android游戏开发的书,并且遇到了第一个代码补丁:
public static class KeyEvent {
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 1;
public int type;
public int keyCode;
public char keyChar;
}
It is my understanding that anything static means there can only be one instance of it. 据我了解,任何静态都意味着只能有一个实例。
If there can only ever be one instance of KeyEvent
why are type
, keyCode
and keyChar
not declared static as well? 如果只能有一个
KeyEvent
实例,为什么type
, keyCode
和keyChar
不能声明为静态?
Only nested classes can be declared as static
; 只有嵌套类可以声明为
static
; not outer/normal classes. 不是外部/普通类。 It allows you to use the static inner class without instantiating the outer class.
它允许您使用静态内部类而无需实例化外部类。
Your code is an nested class
. 您的代码是一个
nested class
。 static
modifier means here that this class is accessible without creating outer class object. static
修饰符在这里意味着无需创建外部类对象即可访问此类。
Assuming that outer class is called OuterClass
you can call: 假设外部类称为
OuterClass
,则可以调用:
KeyEvent ke = new OuterClass.KeyEvent();
static
does not really mean "there can only be one instance of it". static
并不是真正的意思是“只能有一个实例”。
If you are using the static keyword in any declaration within a class, static
means "what I declare here is not a member of an instance of the enclosing class, but it is a member of the class itself ." 如果在类的任何声明中使用static关键字,则
static
表示“我在这里声明的不是封闭类的实例的成员,而是类本身的成员。”
That being said, if you're declaring a nested class (a class within a class) as static, then it means that the nested class declaration does not rely on an instance of the enclosing class, and can be instantiated directly. 话虽如此,如果您将嵌套类(类中的一个类)声明为静态的,则意味着嵌套类声明不依赖于封闭类的实例,并且可以直接实例化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.