java宠物店多态源代码

版权声明:报名咨询QQ:3246333637,本文为 张晨光老师 创作,未经博主允许不得转载 https://blog.csdn.net/zhangchen124/article/details/80936227

Pet类

package com.aaa.adv;
/**
 * 父类:宠物类
 * @author 张晨光
 *
 */
public class Pet {
	//成员变量
	private String name;
	private int health;
	
	//public Pet(){}
	//构造
	public Pet(String name, int health) {
		super();
		this.name = name;
		this.health = health;
	}
	//生成getter/setter;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getHealth() {
		return health;
	}
	public void setHealth(int health) {
		this.health = health;
	}
	
	//增加一个方法:eat
	public void eat(){
		System.out.println("宠物类开始虚拟的吃");
	}
	//针对公共的方法,一定要学会提取出来
	public void eat(String food){
		System.out.println(this.getName()+"吃"+food);
	}
	
	
}

Cat类

package com.aaa.adv;

public class Cat extends Pet {

	public Cat(String name, int health) {
		super(name, health);
	}
	
}

Dog类

package com.aaa.adv;

public class Dog extends Pet {

	public Dog(String name, int health) {
		super(name, health);
		// TODO Auto-generated constructor stub
	}
	//Dog子类,本身仍然保留了父类的eat()不带参数的方法
	
	//子类,增加了一个参数;不再是重写的方法;
//	public void eat(String food){
//		System.out.println("小狗吃"+food);
//	}
}
Parrot类
package com.aaa.adv;
/**
 * 鹦鹉类
 * @author 张晨光
 *
 */
public class Parrot extends Pet {

	public Parrot(String name, int health) {
		super(name, health);
	}
	
}

Rat类

package com.aaa.adv;

public class Rat extends Pet {

	public Rat(String name, int health) {
		super(name, health);
		// TODO Auto-generated constructor stub
	}

}

Master类

package com.aaa.adv;
/**
 * 主人类:姓名 性别 地址 电话 ,本身是不是没有食物的属性;
 * @author 张晨光
 *
 */
public class Master {
	//成员变量;
	//喂养狗;方法(动物,食物)
//	public void feed(Dog dog,String food){
//		dog.eat(food);
//	}
	//喂养猫
//	public void feed(Cat cat,String food){
//		cat.eat(food);
//	}
	//要喂养鹦鹉,需要再次增加鹦鹉的喂养方法;
//	public void feed(Parrot par,String food){
//		par.eat(food);
//	}
	//上面的两个方法,就是上次课说的方法的重载;重载在一个类里面;重写多个类;
	public void feed(Pet pet,String food){
		pet.eat(food);
	}
	
	public static void main(String[] args) {
		//maindog cat自动去eat;
		Dog dog=new Dog("旺财狗",100);
		Cat cat=new Cat("花脸猫",100);
		//增加一个主人类;主人来喂养狗和猫.
		Master master=new Master();
		master.feed(dog,"排骨");
		master.feed(cat,"猫粮");
		//***********增加
		Parrot p=new Parrot("金刚 ",100);
		master.feed(p, "瓜子");
		
		Rat rat=new Rat("米老鼠",100);
		master.feed(rat, "木屑");
	}

}

图示:



阅读更多

扫码向博主提问

tea_year

博客专家

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • Java
  • mysql
  • oracle
  • h5
  • css3
去开通我的Chat快问

没有更多推荐了,返回首页