2

I have some functions collected as methods in a class called func. I use those methods quite often in different classes. Is there a way in java to call those functions without creating a new object or calling it like this: func.myFunction();?

I want: myFunction();

4 Answers 4

2

There are two issues:

  • you can't call non-static methods without having an instance of that class and
  • you can't directly call static methods without mentioning the class name.

The first one is easy to solve: if your method doesn't actually use any non-static members (fields or methods) of the class, then simply adding the static keyword enables you to call it without an instance of the class:

// in YourClass:
public static void yourMethod() {
  //stuff
}

// somewhere else:
YourClass.yourMethod();

And about the second item: I kind-of lied there, you can do that, but you need a static import:

// at the beginning of your .java file
import static yourpackage.YourClass.yourMethod;

// later on in that file:
yourMethod();

Also: there are no functions in Java, only methods.

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

Comments

1

Yes, you can mark the methods as static, and use static imports.

Example:

pkg/UtilFunctions.java

package pkg;

public class UtilFunctions {

    public static int sum(int i1, int i2) {
        return i1 + i2;
    }
}

Test.java

import static pkg.UtilFunctions.*;

class Test {
    public static void main(String[] args) {

        int i = sum(5, 7);     // Calls UtilFunctions.sum(...)

    }
}

Comments

1

Make them static like public static int myFunction(); and then make static import: import static myclass:

Foo.java:
class Foo {
    public static int method() {return 42;}
    ...
}
Bar.java
import static Foo.*;
...
System.out.println(method());

1 Comment

import static myclass won't do, you'll have to import the particular static members of myclass.
0

You can use a static import.

For example this:

import java.lang.Math;
...
System.out.println(Math.abs(-1.4));

and this:

import static java.lang.Math;
...
System.out.println(abs(-1.4));

produce the same result.

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.