Object Parameters in a Constructor

11,862

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.

Share:
11,862
user1310148
Author by

user1310148

Updated on June 04, 2022

Comments

  • user1310148
    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
    Leigh about 12 years
    Yes, class variable implies something different. But good answer otherwise.