Re: To get reference to already existing object from another object



ram wrote:
there [sic] is one class called agent class. there [sic] are methods and
attributes in that class. there is another class called controller
which is in the same context. i [sic] need to access the attributes and
methods of the agent class from the controller class.Please [sic] send me
pointers on this. It would be great if any one could respond.

Hal Rosser wrote:
First I'll assume you misspelled the agent class here and that it is really spelled Agent and I'll assume you misspelled the Controller class as well.

In the main (or other method) in the Controller class you may need to enter some code similar to this:

//create an Agent object
Agent myAgent = new Agent();
//then call the method like this
myAgent.methodName();

It would be great if you provided the code you're working with, and show us what you've tried and what error messages you may have received.

Let's say the Agent has two attributes, call them "fool" and "barb", of types "Foo" and "Bar", respectively. Following good practice, they are private, with public methods to access and mutate their values.

public class Agent
{
private Foo fool;
private Bar barb;
public void setFool( Foo val )
{
this.fool = val;
}
public Foo getFool()
{
return fool;
}
public void setBarb( Bar val )
{
this.barb = val;
}
public Bar getBarb()
{
return barb;
}
}

Then in some method of the Controller we would have a reference to an Agent which would call those methods through its Agent instance:

public class Controller
{
public void execute()
{
Agent agent = new Agent();
agent.setFool( new Foo() );
agent.setBarb( new Bar() );
System.out.println( "Agent Foo = "+ agent.getFool() );
System.out.println( "Agent Bar = "+ agent.getBarb() );
}
}

Just one scenario among an infinitude.

--
Lew
.



Relevant Pages