如何将构造函数参数传递给另一个对象?

2 java oop constructor

我希望这个插图能够清楚地表明我的问题:

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
        }   
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

首先,拥有公共领域是从IMO开始的一个坏主意.(你的名字也不理想......)

您需要做的就是在构造函数中初始化它而不是内联:

private int num;
private final Testing tobj;

public someThread(int num) {
    this.num = num;
    tobj = new Testing(num);
}
Run Code Online (Sandbox Code Playgroud)

(你不必把它作为最终 - 我只是喜欢在我能做的时候让变量最终......)

当然,如果你不需要num任何其他东西,你根本不需要它作为一个领域:

private final Testing tobj;

public someThread(int num) {
    tobj = new Testing(num);
}
Run Code Online (Sandbox Code Playgroud)