Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling static method from another java class

Tags:

java

I've recently switched from working in PHP to Java and have a query. Want to emphasise I'm a beginner in Java.

Essentially I am working in File A (with class A) and want to refer to a static method saved in File B (class B). Do I need to make any reference to File B when working with class A? (I'm thinking along the lines of require_once in PHP) My code in Class A is as follows:

Public class A{
String[] lists = B.staticMethod();
}

Eclipse is not recognising B as a class. Do I need to create an instance of B in order to access the static method. Feel like I'm really overlooking something and would appreciate any input.

like image 296
LeDoc Avatar asked Sep 16 '13 17:09

LeDoc


People also ask

Can you call a static method in another class?

Calling a static method from another classA static method of one class can be invoked from some other class using the class name.

How do you call a static method from another class without using an instance?

Yes it's possible to call static method of a class without using Class reference by using static import. It's preferable to use this way if static methods are used in lot of places in the class.


2 Answers

Ensure you have proper access to B.staticMethod. Perhaps declare it as

public static String[] staticMethod() {
    //code
}

Also, you need to import class B

import foo.bar.B; // use fully qualified path foo.bar.B

public class A {
    String[] lists = B.staticMethod();
}
like image 115
cmd Avatar answered Oct 03 '22 11:10

cmd


You don't need to create an instance of the class to call a static method, but you do need to import the class.

package foo;

//assuming B is in same package
import foo.B;

Public class A{
  String[] lists = B.staticMethod();
}
like image 21
BlakeP Avatar answered Oct 03 '22 12:10

BlakeP