aspose file tools*
The moose likes Beginning Java and the fly likes Accessing the instance of one object from a different class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing the instance of one object from a different class" Watch "Accessing the instance of one object from a different class" New topic
Author

Accessing the instance of one object from a different class

Eric Abadie
Greenhorn

Joined: Dec 08, 2001
Posts: 13
I cant figure out how to call up/access a specific instance of an object from a different class....so if i have an instance of class A floating around...how can an instance of class B read that? ...Note: I dont want to create a new instance of class A within class B
can someone help me please
Eric
Thomas Bigbee
Ranch Hand

Joined: Nov 29, 2001
Posts: 48
The only way you can access an object from within another object is if you have a handle on it - if it's withing another object and you have a handle on that object and that object has access to another (the one you want) other's "get()" method then you can pass the reference on up the line
I know that in one other language that I use you can cycle thru a global listing (a "system object" that holds a listing) of objects in memory until you find the one you want and get a refernece that way - but I don't you can do that in Java
I have pasted some code below to illustrate what I mean by a get method - I could be wrong about what I've just said - however that wont be the first time
Hope that help, Tom

public class Top
{
Middle middleInstance;

Top()
{
middleInstance = new Middle();
}

public static void main(String[] args)
{
Top topInstance = new Top();
topInstance.printBottomString();

}
void printBottomString()
{
System.out.println(middleInstance.returnBottomString());
}
}
class Middle
{
Bottom bottomInstance = new Bottom();
String returnBottomString()
{
return bottomInstance.getBottomString();
}

}
class Bottom
{
String bottomString = "Im a string object in the Bottom class";

String getBottomString()
{
return bottomString;
}

}
------------------
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1751
    
    2
Eric,
I've posted a response over in the Cattle Drive forum.
Mike
Eric Abadie
Greenhorn

Joined: Dec 08, 2001
Posts: 13
thanks for your help guys
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Accessing the instance of one object from a different class