0

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?

  • did you try `A.showA()` – Sharon Ben Asher May 19 '19 at 13:19
  • This code should work, so either you haven’t tested it or you’re not telling us everything. – vandench May 19 '19 at 13:21
  • When you are compiling, are you keeping the __class__ files folder on __classpath__, something on the lines of `javac -classpath .;pathToClassFolder/classFolder -d classFolder *.java`? Then in order to run the program, simply first go inside the __classFolder__ folder, with `cd classFolder` and then run the program with `java ClassWithMainMethod` – nIcE cOw May 19 '19 at 13:24
  • Are you sure that the syntax public void static showC() is correct. As far as I can remember public static void showC() is the correct syntax for a static method – Lebron11 May 19 '19 at 13:25
  • @Lebron11 I’m pretty sure you can rearrange some of the keywords to your liking. I know that IntelliJ IDEA let’s me configure what order I want them to be put in when formatting. – vandench May 19 '19 at 13:28
  • Possible duplicate of [Calling static method from another java class](https://stackoverflow.com/questions/18834005/calling-static-method-from-another-java-class) – dilusha_dasanayaka May 19 '19 at 14:25

1 Answers1

1

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.

Konrad Neitzel
  • 736
  • 3
  • 7