[英]How to instantiate an inner class in Enum?
我想知道如何在枚舉中實例化一個內部類...如果我有這樣的代碼:
public enum TestEnum {
BIG(1),SMALL(2),LARGE(3);
int i;
private TestEnum(int i){
this.i = i;
}
public class cs{
cs c = new cs(){
public void met(){
System.out.println("met in enum inner class");
}
};
}
public static void main(String[] args){
//instantiate an object of cs here
}
}
可以實例化嗎?
由於enum
的內部類是非靜態的,因此需要一個對象引用來創建cs的新實例:
TestEnum.cs sample = TestEnum.BIG.new cs();
// ^^^
// This could be any instance of TestEnum
請注意,如果cs
不使用其“所有者” enum
,則可以使cs
為static
嵌套類。
這將起作用:
TestEnum.BIG.new cs();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.