6 多态
10
李玮玮
开始于 2018-03-29 10:53
0 3 57
已截止

任务尚未发布或者你没有权限查看任务内容。

任务讨论
李玮玮

任务已更新

2-张萌
package net.onest;

public class Animal {
	
	public String name;
	public Animal() {
}
	public Animal(String sname) {
		name = sname;
	}
	public void eat(Food food) {
		String result = this.name + "吃" + food.name;
		System.out.println(result);
	}
	
}


package net.onest;

public class Cat extends Animal{
	
	public String sex; 
	public Cat() {
}
	public Cat(String name,String sex) {
		this.name = name;
		this.sex = sex;
	}
	public void display() {
		System.out.println(name + "性别是" + sex);
	}
	
}


package net.onest;

public class Dog extends Animal{
	
	private int age;  
	public Dog() {
}
	public Dog(String name,int age) {
		this.name = name;
		this.age = age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	public int getAge() {
		return age;
	}
	
}


package net.onest;

public class Elephant extends Animal{
	
	private double weight;  
	public Elephant() {
}
	public Elephant(String eName,double eWeight) {
		name = eName;
		weight = eWeight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	public double getWeight() {
		return weight;
	}
	public void display() {
		System.out.println(name + "的体重是" + weight);
	}
	
}


package net.onest;

public class Person {
	
	public String name;   
	public Person() {}
	public Person(String name) {
		this.name = name;
	}
	public void feed(Animal animal,Food food) {
		System.out.println(name + "喂" + animal.name + "吃" + food.name);
	}
	
}


package net.onest;

public class Test6 {

	public static void main(String[] args) {
		Cat cat = new Cat("猫","母");
		Dog dog = new Dog("狗",6);
		Elephant elephant = new Elephant("大象",100);
		Food food1 = new Food("鱼");
		Food food2 = new Food("肉");
		Food food3 = new Food("香蕉");
		Person person = new Person("刘");
		
		cat.eat(food1);
		dog.eat(food2);
		elephant.eat(food3);
		/*
		person.feed(cat,food1);
		person.feed(dog,food2);
		person.feed(elephant,food3);
		*/
		
	}
	
}