前面练习代码忘了发了,再发一下!
package Ex01;
import java.util.Scanner;
public class Pet {
String name;
int health;
@Override
public String toString() { //重写的toString()方法
return name +"health="+ health;
}
void eat() {
}
}
class Dog extends Pet {
public Dog() {
this.name = "狗狗";
this.health = 80;
}
void skill(){ //狗狗特有技能
System.out.println("我是狗狗,我可以接飞盘!");
}
void eat() {
this.health += 3;
if (this.health >= 100) {
this.health = 100;
}
}
}
class Penguin extends Pet {
public Penguin() {
this.name = "企鹅";
this.health = 80;
}
void skill(){ //企鹅特有技能
System.out.println("我是企鹅,我可以在南极游泳!");
}
void eat() {
this.health += 5;
if (this.health >= 100) {
this.health = 100;
}
}
}
class Master {
void giveFood(Pet a) {
a.eat();
}
public static void main(String[] args) {
Master m = new Master();
Pet d = new Dog();//向上转型
Pet p = new Penguin();//向上转型
if(d instanceof Dog)//用于判断d是否是Dog的实例
((Dog) d).skill() ;//向下转型,执行Dog的特有技能
if(p instanceof Penguin)//用于判断p是否是Penguin的实例
((Penguin) p).skill();//向下转型,执行penguin的特有技能
m.giveFood(d);//主人给d喂食
m.giveFood(p);//主人给p喂食
System.out.println(d.toString());
System.out.println(p.toString());
}
}
package Ex01;
import java.util.Scanner;
public class Human {
public void printGoods(Goods s){
System.out.println(s.name+"的价格为:"+s.price);
}
public static void main(String[] args) {
Goods a=new TVs("电视机",5000);
Goods b=new Foods("奶粉",200);
Human h=new Human();
h.printGoods(a);
h.printGoods(b);
}
}
class Goods {
String name;
double price;
}
class TVs extends Goods{
public TVs( String a, double b) {
this.name=a;
this.price=b;
}
}
class Foods extends Goods{
public Foods(String a, double b) {
this.name=a;
this.price=b;
}
}