2

I hope this illustration will make my question clear:

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
        }   
    }
4

2 回答 2

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);
}
于 2013-01-03T20:10:13.723 回答
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);
        }
于 2013-01-03T20:10:08.810 回答