• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use objects in other classes

 
Moe Kennedy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How is the class Dog defined?
Also what is the code where you are trying to access the getName() method?
 
bhanu chowdary
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please put the complete code.
 
Moe Kennedy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15356
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic