Re: [問題] static nested class
※ 引述《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
推
04/04 16:55, , 1F
04/04 16:55, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):