3

I got some function I would like to use in multiple classes, what is the proper way to do that ?

I thought creating a class and set my functions to static... or maybe implement this class who need these functions ?

What do you think ?

Thanks

3
  • 2
    Please elaborate, what do you mean "use in multiple classes"? Are these methods require some information on the instance? or are they just calculations that are common in your program, and get all they need via parameters? Do these methods change the state of the program? Commented May 4, 2012 at 17:54
  • And what about this "function" (which in Java are called methods) -- what does it do? Is it more of a stateless utility method such as that which can be found in the Math class? Or does it have a state that can change? Commented May 4, 2012 at 17:55
  • Sorry, I was speaking methods like in the Math class. Commented May 4, 2012 at 17:59

4 Answers 4

4

If this method does not use any instance variable of any object, it can (and probably should) indeed be made static, which makes it available from everywhere (provided it's also public).

Good examples of such stateless, globally available methods are the methods from the java.lang.Math class.

Sign up to request clarification or add additional context in comments.

Comments

3

It is typical to implement shared functionality independent of the class instance in a static utility class, the same way that Java implements functionality common to all collections in the java.utils.Collections.

If the functionality depends on the instance, functionality can be shared by placing the implementation in a base class (often an abstract base class), and inheriting it in both classes that need the functionality in question.

Finally, one could implement shared functionality in a package-private utility class, add public methods to both classes calling into that package-private utility class for the implementation.

Comments

1

That depends on the behaviour of the function. For some cases putting function into separate class and making it static is enough. But if you need to modify its behaviour you should consider making it non static in order to allow overriding it in descendant classes.

Comments

0

This is typically achieved using a utility class containing static methods:

class MyCompanyUtils
{
    public static encloseInQuotes(String s)
    {
      /* code to wrap s in quotes */
    }

    public static removeTrailingSlash(String s)
    {
      /* code to remove trailing slash from a string */
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.