[英]How do I pass a constructor parameter to another object?
我希望這個插圖能夠清楚地表明我的問題:
class someThread extends Thread{
private int num;
public Testing tobj = new Testing(num); //How can I pass the value from the constructor here?
public someThread(int num){
this.num=num;
}
void someMethod(){
someThread st = new someThread(num);
st.tobj.print(); //so that I can do this
}
}
首先,擁有公共領域是從IMO開始的一個壞主意。 (你的名字也不理想......)
您需要做的就是在構造函數中初始化它而不是內聯:
private int num;
private final Testing tobj;
public someThread(int num) {
this.num = num;
tobj = new Testing(num);
}
(你不必把它作為最終決定 - 我只是喜歡在我能做的時候讓變量最終......)
當然,如果你不需要其他任何num
,你根本不需要它作為一個字段:
private final Testing tobj;
public someThread(int num) {
tobj = new Testing(num);
}
為什么不在構造函數中初始化對象?
public Testing tobj ; //How can I pass the value from the constructor here?
public someThread(int num){
this.num=num;
tobj = new Testing(this.num);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.