问题
first of all I apologize if my question is difficult to understand. I'm having a hard time trying to explain exactly what I need help with. I am new to Java and the concept of passing by reference etc.
Basically, I need to know why the below code is incorrect. How do I tell Java to use a method for an object passed in as a parameter of the constructor? Apologies again, and thanks for reading!
public ClassOne(ClassTwo twoObject){
}
public boolean OneMethod(){
twoObject.MethodName(); // twoObject cannot be resolved.
}
回答1:
You are using a local object in another method it isnt working, You can create an global object to save it and then use it...
public class classOne{
Classtwo object;
public ClassOne(ClassTwo twoObject){
object = twoObject;
}
public boolean OneMethod(){
object.MethodName();
}
}
Hope it helps you :)
回答2:
You would need to store a reference to twoObject locally within the instance of this class in order to access it outside the scope of the constructor. Right now the constructor executes with the passed item, does nothing and the instance of twoObject disappears from this class for all practical purposes.
回答3:
The code is incorrect as "twoObject" is not in scope when its method "MethodName" is called. It was in scope if used in the constructor , but is not in scope in the method "OneMethod". To use it you can create a class variable and assign it to "twoOject" in the constructor. You can then use it throughout your class.
public ClassOne {
private ClassTwo twoObject; // instance variable
public ClassOne(ClassTwo twoObject){
this.twoObject=twoObject;
}
public boolean OneMethod(){
twoObject.MethodName(); // twoObject is now a class memeber and hence in scope and hence will be resolved
return true; //could also be false, just adding a return statement as the return type is boolean
}
}
来源:https://stackoverflow.com/questions/9991503/object-parameters-in-a-constructor