import java.util.Random; public class Text1 { abstract class Pet { public abstract void playSound(); } static class Dog extends Pet{ @Override public void playSound() { System.out.println("汪汪....汪"); } } static class Cat extends Pet{ @Override public void playSound() { System.out.println("喵喵.....喵"); } } static class Sheep extends Pet{ @Override public void playSound() { System.out.println("咩咩.....咩"); } } public static void main(String[] args) { Random rand=new Random(); Dog dog=null; Cat cat; Sheep sheep; for(int i=1;i<=5;i++){ int m=rand.nextInt(3); switch(m){ case 1: dog=new Dog(); dog.playSound(); break; case 2: cat=new Cat(); cat.playSound(); break; case 3: sheep=new Sheep(); sheep.playSound(); break; } } } }
import java.util.Random;
public class Text1 {
abstract class Pet {
public abstract void playSound();
}
static class Dog extends Pet{
@Override
public void playSound() {
System.out.println("汪汪....汪");
}
}
static class Cat extends Pet{
@Override
public void playSound() {
System.out.println("喵喵.....喵");
}
}
static class Sheep extends Pet{
@Override
public void playSound() {
System.out.println("咩咩.....咩");
}
}
public static void main(String[] args) {
Random rand=new Random();
Dog dog=null;
Cat cat;
Sheep sheep;
for(int i=1;i<=5;i++){
int m=rand.nextInt(3);
switch(m){
case 1:
dog=new Dog();
dog.playSound();
break;
case 2:
cat=new Cat();
cat.playSound();
break;
case 3:
sheep=new Sheep();
sheep.playSound();
break;
}
}
}
}
我是一名刚接触Java的小白,刚学到多态,就是它编译后,就出现标题的,想问一下,这种问题怎么解决