快考试了帮帮我吧,java题目

2024-11-17 20:20:59
推荐回答(2个)
回答1:

public class AnimalDemo {
public void test(){
Animal animalDog = new Dog();
Animal animalCat = new Cat();

animalDog.sound();
animalCat.sound();
}
}

public class Animal {
public void sound(){
System.out.println("animal sound");
}
}

public class Dog extends Animal{
@Override
public void sound() {
// TODO Auto-generated method stub
System.out.println("Dog sound");
}
}

public class Cat extends Animal{
@Override
public void sound() {
// TODO Auto-generated method stub
System.out.println("Cat sound");
}
}

回答2:

//定义一个动物类
public class animal{
//定义动物类型
String type[]={"猫","狗"};
public void sound(){
System.out.println("this is super class");
}
}
//定义一个Dog类
public class Dog extends Animal{
public void sound(){
System.out.println("我是dog,覆盖了Animal的方法");
}
}
//定义一个猫类
public class Cat extends Animal{
public void sound(){
System.out.println("我是cat,覆盖了Animal的方法");
}
}
public class AnimalDemo{
Animal animal=null;
public static void main(String args[]){
//多态创建一只狗,此时animal表示一只狗
animal=new Dog();
animal.sound();
//多态创建一只猫,此时animal表示一只猫
animal=new Cat();
animal.sound();
}
}