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.
Calling a static method from another classA static method of one class can be invoked from some other class using the class name.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With