Object Parameters in a Constructor
Solution 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 :)
Solution 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.
user1310148
Updated on June 04, 2022Comments
-
user1310148 almost 2 years
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. }
-
Leigh about 12 yearsYes, class variable implies something different. But good answer otherwise.