我希望这个插图能够清楚地表明我的问题:
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
}
}
答案 0 :(得分:6)
首先,拥有公共领域是从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);
}
答案 1 :(得分:1)
为什么不在构造函数中初始化对象?
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);
}