abstract class and duotai

package

demo.duotai;

 

public

abstract class Pet {

private int health;

 

public Pet(int health) {

this.health = health;

}

 

public int getHealth() {

if (health > 0) {

return health;

} else {

System.out.println("that is an unvalid number");

return 0;

}

}

 

public void setHealth(int health) {

this.health = health;

}

 

public abstract void toHospital();

 

}

 ------------------------------------

package

demo.duotai.impl;

 

import

demo.duotai.Pet;

 

public

class Dog extends Pet {

public Dog(int health) {

super(health);

// TODO Auto-generated constructor stub

}

 

public void toHospital(){

this.setHealth(50);

System.out.println(getHealth() + " " + "inject, medical");

}

 

public void dogFun(){

 

System.out.println("dog fun");

}

}

-----------------------------

package

demo.duotai.impl;

 

import

demo.duotai.Pet;

 

public

class Penguin extends Pet {

public Penguin(int health) {

super(health);

}

 

public void toHospital(){

//this.setHealth(50);

System.out.println(this.getHealth() + " " + "medical, rest");

}

 

public

void penguinFun(){

 

System.out.println("Penguin fun");

}

}

------------------

package

demo.duotai.impl;

 

import

demo.duotai.Pet;

 

public

class Cat extends Pet {

public Cat(int health) {

super(health);

// TODO Auto-generated constructor stub

}

 

public void toHospital() {

this.setHealth(30);

System.out.println(getHealth() + " " + "cat cure method");

}

}

------------------------

package

demo.duotai;

 

import

demo.duotai.impl.Cat;

import

demo.duotai.impl.Dog;

import

demo.duotai.impl.Penguin;

 

public

class Master {

 

public void Cure(Pet pet) {

 

pet.toHospital();

}

 

public static void main(String[] args) {

// Pet pet = new Penguin();

// Pet pet1 = new Dog();

// Pet pet3 = new Cat();

// Master master = new Master();

//

// master.Cure(pet);

// master.Cure(pet1);

// master.Cure(pet3);

 

Pet pet = new Penguin(100);

Master master = new Master();

master.Cure(pet);

 

pet = new Dog(70);

master.Cure(pet);

 

if (pet instanceof Dog) {

((Dog) pet).dogFun();

} else if (pet instanceof Penguin) {

Penguin penguin = (Penguin) pet;

penguin.penguinFun();

}

// pet = new Cat();

// master.Cure(pet);

 

}

}

原文地址:https://www.cnblogs.com/mabel/p/5916958.html