我想玩類實例化和this
。在其他地方實例化的類,這用於訪問它
在下面的例子中,testresult
類將被實例化和存儲。將使用 this
將該類實例作爲參數傳遞給另一個類。
這是this
的正確用法,因爲類在其他地方被實例化了嗎? 不確定爲什麼我看到錯誤爲「構造函數testfail(new Handler(){})
未定義」。
代碼片段:
public class testmain {
private testresult tr;
private testfunc tf;
public testmain() {
tr = new testresult();
tf = new testfunc(tr);
}
}
public class testfunc {
private testresult storeit;
public testfunc(testresult inst) {
storeit = inst;
}
// this will be running as seperate thread running forever.
}
public class testresult {
private testfail tp;
public void function() {
tp = new testfail(this); //----> error new Handler(){} undefined
}
}
public class testfail {
public testfail(testresult tr) {
///
}
}
編輯:該錯誤是由於內部類
public class testresult {
private testfail tp;
private class test {
public void function() {
tp = new testfail(this); ----> error
// new Handler(){} undefined
}
}
}
錯誤具體是,你不必有處理程序對象作爲參數的構造函數。這是因爲你對'this'的引用可能是指稱爲'function()'的函數。 作爲一個側面說明,像你這樣的類之間的循環引用不是一個偉大的設計,應該重新設計。 –
是的,我在代碼中的另一個私有類中寫了function(),因此「this」指的是內部私有類,而不是我想要的那個。 – cyne