1

Is there a way to call a method in one class from another class. I could have say 5 classes and more than one may want to perform the same operation. So can I have one file (class??) with these common methods and call into that? If so what is the necessary modifier for these 'common' methods - public, final??

If anyone can point me to a suitable tutorial I would be grateful - in this instance I havent had much useful from Google Thanks Ron

ron
  • 5,219
  • 8
  • 39
  • 44
  • Never having developed in Android is it not as standard as creating an instance of the type and calling the public method exposed on the type? – Aaron McIver Jan 04 '11 at 15:11
  • It is not an Android question, it is a general one! See that thread, it will give you a glance of that you need to read - http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read – Kiril Kirilov Jan 04 '11 at 15:13
  • Those common methods should be static and public. You can also mark them as final, but it's a matter of preference in this context. – Eli Acherkan Jan 04 '11 at 15:16

4 Answers4

1

I'd go with a general tutorial on OOP and how to use classes, e.g.
http://download.oracle.com/javase/tutorial/java/javaOO/classes.html

Basically you can call any method from another class, as long as it's public. If the method is static, you don't even need to instantiate it. But read some tutorials to get the basic idea of OOP instead of just looking for a solution for your specific problem, it'll help a lot more!

Select0r
  • 12,234
  • 11
  • 45
  • 68
1

This is a simple example for a (utility) class with a method that can be used from any other class:

public class Util {
   public static int sizeOf(String input) {
     return input.size();
   }
}

To make it work "right out of the box": choose public and static as access modifiers for the method. Just like all methods from the well known java.lang.Math class.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

You probably want to create a "Utility" class. You can use the static keyword to make your methods static:

public UtilityClass {

   public static int myMethod(String arg) {
   }
}

result = UtilityClass.myMethod("sdfs");

In the implementation of the static methods you can't use local fields, unless you also mark them as static.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
0

You can either make these methods public static. An other way would be to pass instances of these other classes into your class. Maybe as a method parameter, set-method or parameter of the constructor.

codymanix
  • 28,510
  • 21
  • 92
  • 151