【问题标题】:Received error when copying example code to eclipse JAVA将示例代码复制到 Eclipse JAVA 时收到错误
【发布时间】:2021-08-17 13:20:01
【问题描述】:
class Animal {
    public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();
    Animal myPig = new Pig();
    Animal myDog = new Dog();
        
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

所以我从 w3schools 复制并粘贴了这段代码。我将文件命名为 polymorphism.java,但是当我在命令提示符下运行它时,它给了我这个错误:在类中找不到 main(String[]) 方法:Animal 我需要改变什么?

【问题讨论】:

    标签: java class


    【解决方案1】:

    从错误消息中,我们看到 java 正在寻找类 Animal 中的方法 main(String[])。现在,如果我们查看您粘贴的代码,我们可以看到 Animal 类确实没有这个方法。 Main 类有这个方法。您需要指定在Main 类而不是Animal 类中查找main 方法。

    【讨论】:

    • 嗯,我该怎么做,哈哈。抱歉,我对这些东西不熟悉。
    • stackoverflow.com/a/32439530/10741530这个答案会解决你的问题。
    • 嗯,我刚刚将 Main 类移到顶部,它起作用了...
    【解决方案2】:

    您应该在覆盖方法后提供@Override 注释。 为我工作:

    class Animal1 {
        public void animalSound() {
        System.out.println("The animal makes a sound");
      }
    }
    
    class Pig extends Animal1 {
        
      @Override 
      public void animalSound() {
        System.out.println("The pig says: wee wee");
      }
    }
    
    class Dog extends Animal1 {
      @Override
      public void animalSound() {
        System.out.println("The dog says: bow wow");
      }
    }
    
    class Main extends Dog {
      public static void main(String[] args) {
    
          Animal1 d = new Animal1();
          d.animalSound();
          Animal1 myPig = new Pig();
            Animal1 myDog = new Dog();
                
            d.animalSound();
            myPig.animalSound();
            myDog.animalSound();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多