作者awert ( )
看板java
标题Re: [问题] static nested class
时间Wed Apr 4 16:41:33 2012
※ 引述《singlovesong (~"~)》之铭言:
: 在网路上找了一些资料 大概了解static nested class 的用法
: 只是有一点不太清楚的是
: 如果他被看成是 outer class的static member
: 那麽为什麽还可以去new 它呢?
: 一般的class 里面的static variable or method 是class level 的
: 应该只有一份copy 才对?
: e.g:
: class A{
: static class B{
: void Print(){
: }
: }
: }
你文中提到的「只有一份 "copy"」是指 static field 特性,并不是说只要叫
static 就只能有一个存在。
JLS : 8.3.1.1. static Fields
If a field is declared static, there exists exactly one incarnation of the
field, no matter how many instances (possibly zero) of the class may
eventually be created. A static field, sometimes called a class variable, is
incarnated when the class is initialized.
static 真正的意思应为,一个宣告为 static 的 member (nested class/method/field)
可以不需要透过某个 outer class instance 的 reference 就能使用
public class TopLevel {
public static int X = 1;
public int y = 2;
public static class StaticNestedClass {
}
public class C InnerClass {
}
}
public static void main(String[] args) {
TopLevel.StaticNestedClass a = new TopLevel.StaticNestedClass(); // ok!
System.out.println(TopLevel.X); // print 1
TopLevel.InnerClass b = new TopLevel.InnerClass(); // compile error
System.out.println(TopLevel.y); // compile error
TopLevel top = new TopLevel();
TopLevel.InnerClass b = top.new TopLevel.InnerClass(); // ok!
System.out.println(top.y); // print 2
}
但相对的,一个 static member 没有办法去存取 outer class ,因为没有 instance
reference 存在。
public class TopLevel {
private int x = 3;
public static class StaticNestedClass {
private int y = x + 1; // compile error
}
public class InnerClass {
private int z = x + 1; // ok!
}
}
--
We who cut mere stones must always be envisioning cathedrals.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.27.160.138
1F:推 singlovesong:谢谢你! 04/04 16:55