需求:请采用多种思想实现猫和狗的案例,并在测试类中进行测试。
代码演示:(采用多态的思想)
动物类:
public class Animal {
private String name;
private int age;
public Animal() {
}
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void eat() {
System.out.println("动物吃东西");
}
}
猫类:
public class Cat extends Animal{
public Cat() {
}
public Cat(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
狗类:
public class Dog extends Animal{
public Dog() {
}
public Dog(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("狗吃骨头");
}
}
测试类:
public class AnimalDemo {
public static void main(String[] args) {
//创建猫类对象进行测试
Animal a = new Cat();
a.setName("加菲");
a.setAge(5);
System.out.println(a.getName()+","+a.getAge());
a.eat();
a = new Cat("加菲", 5);
System.out.println(a.getName()+","+a.getAge());
a.eat();
//创建狗类对象进行测试
Animal a1 = new Dog();
a1.setName("哈士奇");
a1.setAge(3);
System.out.println(a1.getName()+","+a1.getAge());
a1.eat();
a1 = new Dog("哈士奇", 3);
System.out.println(a1.getName()+","+a1.getAge());
a1.eat();
}
}
运行结果:
加菲,5
猫吃鱼
加菲,5
猫吃鱼
哈士奇,3
狗吃骨头
哈士奇,3
狗吃骨头
(采用抽象的思想)
动物类:
public abstract class Animal {
private int age;
private String name;
public Animal() {
super();
}
public Animal(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void eat();
}
猫类:
public class Cat extends Animal{
public Cat() {
}
public Cat(int age, String name) {
super(age, name);
}
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
狗类:
public class Dog extends Animal{
public Dog() {
}
public Dog(int age, String name) {
super(age, name);
}
public void eat() {
System.out.println("狗吃骨头");
}
}
测试类:
public class AnimalDemo {
public static void main(String[] args) {
//创建对象,按照多态的方式
Animal a = new Cat();
a.setName("加菲");
a.setAge(5);
System.out.println(a.getName()+","+a.getAge());
a.eat();
System.out.println("--------");
a = new Cat(5, "加菲");
System.out.println(a.getName()+","+a.getAge());
a.eat();
System.out.println("-------------");
Animal a1 = new Dog();
a1.setName("哈士奇");
a1.setAge(6);
System.out.println(a1.getName()+","+a1.getAge());
a1.eat();
System.out.println("--------");
a1 = new Dog(6, "哈士奇");
System.out.println(a1.getName()+","+a1.getAge());
a1.eat();
}
}
运行结果:
加菲,5
猫吃鱼
--------
加菲,5
猫吃鱼
-------------
哈士奇,6
狗吃骨头
--------
哈士奇,6
狗吃骨头