Shinao
Shinao

Reputation: 137

Using same function in multiple class

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

Upvotes: 3

Views: 3881

Answers (4)

jahroy
jahroy

Reputation: 22692

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 */
    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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.

Upvotes: 3

michael nesterenko
michael nesterenko

Reputation: 14439

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.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

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.

Upvotes: 4

Related Questions