-1
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();
  }
}

So I copied and pasted this piece of code from w3schools. I named the file polymorphism.java, but when i run it on command prompt, it gives me this error: can't find main(String[]) method in class: Animal What do I need to change?

General Pleather
  • 125
  • 1
  • 1
  • 6

2 Answers2

0

From error message we see that java is looking for method main(String[]) in class Animal. Now if we look into code you pasted we can see that indeed Animal class doesn't have this method. Class Main has this method. You need to specify to look for main method in Main class instead of Animal class.

0

you should provide the @Override annotation after overriding the methods. Works for me:

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();
  }
}
Abhishek
  • 423
  • 6
  • 12