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
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
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.
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.