javafunctionmethodsglobal

Java function (method) available everywhere (global)


I've recently (4 days ago) started programming in JAVA. I have some overall programming experience from C++ and PHP. My question is: can we implement a function in JAVA, that is available in all classes? I'm thinking of some global logging function, that I need to call in several places (log events, errors, etc.).

Imagine I have two classes, A and B. I need to call logging function in both of them, but I don't want to copy whole function body (awful thing I believe), and I want to call it strict (without creating another class, instantiating it, and then calling from the instance), like logEvent(someVariable). So I should use an abstract class C, which A and B will extend, BUT they are already an extension of other class (built-in). Since multiple inheritance isn't allowed (is it?), I need to do some trick. Singleton is not pleasing me too. In PHP or C++ I would just create separate file with function body and then include it.

Here is how I want to use it:

public class A extends SomeClass {
    String error = "Error from class A";
    logEvent(error);
}

public class B extends SomeOtherClass {
    String error = "Error from class B";
    logEvent(error);
}

Solution

  • Put a static method in any class (it could be a utils class, or whatever), then call it like this: ClassName.functionName()

    Static methods belong to the class, not instances of the class, so you don't need to instantiate the class to access the method

    But everything in Java has to be in a class, so you can't access it without the class name.