Java(15) 多态

一.多态

 1.1 多态:一个事物的多种形态

 1.2 多态的表现

行为(方法)多态:重写和重载。

引用多态(动态绑定):编译时的类型和运行时不一致的这种现象

例:父类 = 子类

Pet p = new Dog();

  向上转型;父类=子类

   例:Pet p = new Dog();

向下转型:子类 = (子类)父类

例: Dog d = (Dog)p;

 public abstract class Pet {
private String name;
private int health=100;
private int age;
private int love=50;
public Pet(){ }
public Pet(String name,int health,int age,int love){
this.name = name;
this.health = health;
this.age = age;
this.love = love;
}
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;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int getLove(){
return love;
}
public void setLove(int love){
this.love = love;
}
public void ji(){
System.out.println("宠物的自白:我的名字叫:"+this.name+",年龄为:"+this.age+"和主人的亲密度为:"+this.love);
}
public abstract void eat();
}

宠物抽象类

 public class Dog extends Pet{
private String strain;
public Dog(){ }
public Dog(String name,int health,int age,int love,String strain){
super(name,health,age,love);
this.strain = strain;
}
public void catchingFlyDisc(){
System.out.println("接飞盘");
int health = getHealth();
health = health-10;
setHealth(health); int love = getLove();
love = love+5;
setLove(love);
}
public void eat(){
System.out.println("狗狗吃鱼");
}
public String getStrain(){
return strain;
}
public void setStrain(String strain){
this.strain = strain;
} }

狗狗类继承宠物类

 public class Penguin extends Pet {
private String sex;
public Penguin(){ }
public Penguin(String name,int health,int age,int love,String sex){
super(name,health,age,love);
this.sex = sex;
}
public void swimming(){
System.out.println("游泳");
int health = getHealth();
health = health-10;
setHealth(health); int love = getLove();
love = love+5;
setLove(love);
}
public void eat(){
System.out.println("企鹅喝水");
}
public String getSex(){
return sex;
}
public void setSex(String sex){
this.sex = sex;
} }

企鹅类继承宠物类

 public class Master {
public void feed(Pet p){
p.eat();
}
public void play(Pet p){
if(p instanceof Dog ){
Dog d = (Dog) p;
d.catchingFlyDisc();
}else if(p instanceof Penguin){
Penguin pe = (Penguin) p;
pe.swimming();
}
}
}

主人类

 public class TestPMPD {
public static void main(String[] args){
Master m= new Master();
//向下转型
Pet p = new Dog();
Dog d = (Dog) p;
m.feed(d);
// Pet p = new Penguin();
// m.feed(p);
}
}

测试类

运行结果为:Java(15) 多态

注意:java.lang.ClassCastException:类型转换异常

父类的运行时类型跟要转成的子类的类型不一致

注意:引用多态存在继承关系

二.instanceof

语法: 对象A instanceof 类型B

判断对象A的类型是否是类型B,是就返回true,否则返回false

例:d instanceof Dog

三.实现多态的2种形式

a.使用父类作为方法形参实现多态

public void play(Pet p){...}

b.使用父类作为方法返回值实现多态

public Pet getPet(int type){...}

上一篇:已超过传入消息(65536)的最大消息大小配额。若要增加配额,请使用相应绑定元素上的 MaxReceivedMessageSize 属性。


下一篇:SharpGL学习笔记(三) 投影变换和视点变换