简体   繁体   中英

Java - Cannot Find Symbol Error With Other Classes

First and foremost I want to make myself clear: I am not asking what the cannot find symbol error means, I am simply asking what is causing this error in this context.

I have recently delved into classes in Java. Below is my first [non main ] class:

class Test {
    public void test() {
        System.out.println("Hello, world!");
    }
}
class Main {
    public static void main(String[] args) {
        test();
    }
}

But I get the following error:

exit status 1
Main.java:8: error: cannot find symbol
                test();
                ^
  symbol:   method test()
  location: class Main
1 error

Can anyone please explain why this happens?

System.out.println("Thanks!");

The method test() is not declared static.

You are calling a non-static method test() in a static method main(). If you do not want to change the class Test you have to change main() as follow

public static void main(String[] args) {
    Test t = new Test();
    t.test();
}

If you do not want to change main() too much. Then you have to change the test() method as follow: public static void test() {}

and the inside the main() method:

Test.test()

You cant use test() method in Main class. Because test() method defined in another class, in Test class. To reach test() method in other class (Main class), you have to create an object and you can reach test() method through this object. test() method is an instance method which belongs to Test class.

class Main {
  public static void main(String[] args) {
      Test test1 = new Test();
      test1.test();
  }
}

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