为什么在 main 方法中没有检测到我的方法?

Why is my method not being detected in the main method?

我只是在测试一些继承,但似乎我的方法没有被调用,甚至没有被 main 方法看到。它编译,但只是说文件中没有检测到方法。我的代码有什么问题?

public class monkey
{
    public void main(String[] args){
          Fruit jeff = new Fruit("ree");
          Fruit mike = new Apple("ree");

          jeff.talk();
          mike.talk();
    }

class Fruit 
{ 
    String sound;
    public Fruit(String s) { 
      sound = s;
    } 

    public void talk(){
      System.out.print(sound);
    }
} 

class Apple extends Fruit 
{ 
   public Apple(String s){
      super(s);
   }
}
}
  • 将 static 放在 main 方法签名中。
  • 创建静态内部 类 因为你想在静态 main 方法中访问那些 类。

正确代码:

public class monkey {
    public static void main(String[] args) {
        Fruit jeff = new Fruit("ree");
        Fruit mike = new Apple("ree");

        jeff.talk();
        mike.talk();
    }

    static class  Fruit {
        String sound;

        public Fruit(String s) {
            sound = s;
        }

        public void talk() {
            System.out.print(sound);
        }
    }

    static class Apple extends Fruit {
        public Apple(String s) {
            super(s);
        }
    }
}