Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How do you use something that is in another java class?  RSS feed

 
Justin Robbins
Ranch Hand
Posts: 121
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure if it's even called another class. But you know how you have eclipse with one page that has the main method and some stuff then you have another page with some stuff. How do you get the stuff that's defined in the main method page and start applying it to the stuff that's in the other page. I know this must sound vague and it's because I am so new to Java I don't know what the technical names for all these things are.
I know all projects or packages? have to have at least one main method.
So I have class that looks like this:



Then I have another page I created that has a single class like this:


How am I able to use the stuff I defined in the main method and start using it in this other class or method? like say I want to access something about 's' that was defined in the main method but I want to access it through my Cats class/method. How would that be accomplished?


Thank you
 
Carey Brown
Bartender
Posts: 2980
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
's' is a variable that is local to your main(). Cats has no direct way to access it. However you can let an instance of Cats get a copy of the value stored in 's' by passing it to a Cats constructor, passing in to a method of Cats, or passing to a setter of Cats.

As an aside, 's' is a horrible variable name. 's' is often used as a temporary variable name for a String. 'i' would be a better name for a temporary int variable. And it would be much better to use a descriptive variable name.
 
Knute Snortum
Sheriff
Posts: 4070
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To illustrate one of the methods Carey spoke of:


In the class Cats, you add a parameter (a) to the method signature. You then use "a" however you like in the method.

In the class Dogs, you create a new instance of Cats (an object) and from that you can call the error method in Cats. Note that the "s" in cats.error(s) is called an argument. The "a" in error(int a) is called a parameter. Note also that the argument and the parameter do not have to have the same name.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!