Calling static method from another java class

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.


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

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

Java has classloader mechanism that is kind of similar to PHP's autoloader. This means that you don't need anything like a include or require function: as long as the classes that you use are on the "classpath" they will be found.

Some people will say that you have to use the import statement. That's not true; import does nothing but give you a way to refer to classes with their short names, so that you don't have to repeat the package name every time.

For example, code in a program that works with the ArrayList and Date classes could be written like this:

java.util.ArrayList<java.util.Date> list = new java.util.ArrayList<>();
list.add(new java.util.Date());

Repeating the package name gets tiring after a while so we can use import to tell the compiler we want to refer to these classes by their short name:

import java.util.*;
....
ArrayList<Date> list = new ArrayList<>();
list.add(new Date());