aspose file tools*
The moose likes Beginning Java and the fly likes Use objects in other classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Use objects in other classes" Watch "Use objects in other classes" New topic
Author

Use objects in other classes

Moe Kennedy
Greenhorn

Joined: Aug 29, 2011
Posts: 7
Hello
Im trying to use an object in an other class.
Example:

That works fine. But in an other Class I have to get the name of the object dog1. How can I do that?
"dog1.getName" of course doesn't work...

Greetings From Switzerland
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3068
    
  33

How is the class Dog defined?
Also what is the code where you are trying to access the getName() method?


Mohamed Sanaulla | My Blog
bhanu chowdary
Ranch Hand

Joined: Mar 09, 2010
Posts: 256
Please put the complete code.
Moe Kennedy
Greenhorn

Joined: Aug 29, 2011
Posts: 7
Here is the code from the class dog:


This is the test1:

That works fine. But now I have to get the name from the dog1. But I'm in another class.
I tried this, but it wont work:

bhanu chowdary
Ranch Hand

Joined: Mar 09, 2010
Posts: 256
Moe Kennedy wrote:But now I have to get the name from the dog1. But I'm in another class.
I tried this, but it wont work:



This will not work Moe. The dog1 which you have created in class Test1 is only confined to the main method in Test1. You cannot use it from Test2.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14107
    
  16

If Test2 is a completely separate program, that you start separately (it looks that way because it has its own main() method), then you cannot get to the dog1 variable that was declared in Test1.

If Test1 and Test2 are part of the same program then you do it by passing a reference to the created dog object from one class to the other. For example:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Use objects in other classes