开发者

Java: having files containing only general methods?

开发者 https://www.devze.com 2023-04-12 10:44 出处:网络
I was wondering if there was a way to ha开发者_开发百科ve methods separated from the main and class files (like how in c you can have .c & .h with just methods that you can import into projects).

I was wondering if there was a way to ha开发者_开发百科ve methods separated from the main and class files (like how in c you can have .c & .h with just methods that you can import into projects).

Specifically I have a 'logical exclusive or' function that I want to use across several classes and I thought it would be good practice not to have the same function repeated across several classes.


They're called function libraries and yes you can do them. The best example is java.lang.Math.

You make a final class with a private constructor, no variables, and all static methods.

public final class FuncLib {

    private FuncLib() { } // prevents instantiation

    public static String formatAwesomely(String foo) {
        // code
    }

    public static int calculateScore(BaseballGameData data) {
        // code
    }

}


In Java, you have to shove everything into a class. The general convention is having a class named Utils (or BooleanUtils or whatever organisation / naming convention you like) and putting generic pure functions into it as static methods.

Java 5 and later have a static import feature to make using this sort of functions less verbose.


With Java being an object-oriented language you might want to think about what your goal is. Traditionally with object-oriented design, if multiple objects really do have a single common ancestor method which is common across them, in all likely hood all of those classes should be sub-classes of that class.

Example:

Think about animals, lets say we have a dog and a cat. All animals make noises. You might have a method for "makeNoise()" which both classes need. A common setup would then to have one class of "Animal" and two sub-classes which extend the "Animal" class named "Dog" and "Cat".

In this case if the "makeNoise()" method as it stands for all animals is adequate for your more specific classes, then that is fine for them to use. Additionally, perhaps a cat and a dog make a noise in the same way (from their mouth) but in the end it is a different noise (bark vs meow) and you can choose to override your "makeNoise()" method with any class specific attributes.

0

精彩评论

暂无评论...
验证码 换一张
取 消