Droider
Droider

Reputation: 123

Use Functions in different classes in Java without collecting it in a class as methods

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();

Upvotes: 2

Views: 199

Answers (4)

nmikhailov
nmikhailov

Reputation: 1423

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());

Upvotes: 1

aioobe
aioobe

Reputation: 420991

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

    }
}

Upvotes: 1

Petar Ivanov
Petar Ivanov

Reputation: 93030

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.

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308031

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.

Upvotes: 2

Related Questions