3 回答

TA貢獻1783條經驗 獲得超4個贊
從技術上講,沒有,因為匿名類不能具有構造函數。
但是,類可以引用包含范圍的變量。對于匿名類,這些可以是包含類的實例變量,也可以是標記為final的局部變量。
編輯:正如彼得指出,您還可以將參數傳遞給匿名類的超類的構造函數。

TA貢獻1856條經驗 獲得超11個贊
是的,通過添加一個返回“ this”的初始化方法并立即調用該方法:
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
private int anonVar;
public void actionPerformed(ActionEvent e) {
// How would one access myVariable here?
// It's now here:
System.out.println("Initialized with value: " + anonVar);
}
private ActionListener init(int var){
anonVar = var;
return this;
}
}.init(myVariable) );
無需“最終”聲明。

TA貢獻1853條經驗 獲得超6個贊
這會做魔術
int myVariable = 1;
myButton.addActionListener(new ActionListener() {
int myVariable;
public void actionPerformed(ActionEvent e) {
// myVariable ...
}
public ActionListener setParams(int myVariable) {
this.myVariable = myVariable;
return this;
}
}.setParams(myVariable));
添加回答
舉報