简体   繁体   中英

How can a class in a package use other classes in the same package's static methods?

I have classes A and C in package abc. A has a static method showA(). Now I want to use this method in C.How do I do this?

package abc;
public class A{
    public void static showA()
        System.out.println("I am in A");
    }
}

package abc;
public class C{
    public void static showC(){
        A.showA();
        System.out.println("I am in C");
    }
}

Now while compiling C it shows that, cannot find variable A. How to resolve this?

You didn't give exact information about what you did, but I fear that you are compiling the classes one by one with calls like

javac abc/A.java
javac abc/B.java

You have 2 possibilities: The first one is to tell the compiler to compile both classes. That way both classes will be known:

javac abc/A.java abc/B.java

Another possibility is to tell the compiler where the required class file can be found. As A.Java is compiled to A.class with the same base directory, you could do the calls:

javac abc/A.java
javac -cp . abc/B.java

With -cp you add the local directory to the classpath so A.class is on the classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM