Calling static method from another java class

前端 未结 3 1549
执笔经年
执笔经年 2020-11-28 15:14

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) a

相关标签:
3条回答
  • 2020-11-28 15:22

    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();
    }
    
    0 讨论(0)
  • 2020-11-28 15:36

    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();
    }
    
    0 讨论(0)
  • 2020-11-28 15:38

    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());
    
    0 讨论(0)
提交回复
热议问题