day09-引用数据类型转换(向上转型和向下转型)
This commit is contained in:
9
day10/src/com/inmind/duotai08/downcast/Animal.java
Normal file
9
day10/src/com/inmind/duotai08/downcast/Animal.java
Normal file
@@ -0,0 +1,9 @@
|
||||
package com.inmind.duotai08.downcast;
|
||||
|
||||
public abstract class Animal {
|
||||
String name;
|
||||
int age;
|
||||
|
||||
//吃的行为
|
||||
public abstract void eat();
|
||||
}
|
||||
12
day10/src/com/inmind/duotai08/downcast/Cat.java
Normal file
12
day10/src/com/inmind/duotai08/downcast/Cat.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.inmind.duotai08.downcast;
|
||||
|
||||
public class Cat extends Animal{
|
||||
@Override
|
||||
public void eat() {
|
||||
System.out.println("猫吃鱼");
|
||||
}
|
||||
|
||||
public void catchMouse(){
|
||||
System.out.println("猫抓老鼠");
|
||||
}
|
||||
}
|
||||
23
day10/src/com/inmind/duotai08/downcast/Demo10.java
Normal file
23
day10/src/com/inmind/duotai08/downcast/Demo10.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package com.inmind.duotai08.downcast;
|
||||
/*
|
||||
学习的对象的向上转型和向下转型,也就是引用数据类型的数据类型转换(自动转换和强制类型转换)
|
||||
|
||||
注意:多态的向下转型时,一定要是对应的类型才能转换,否则会报错java.lang.ClassCastException(类型转换异常)
|
||||
*/
|
||||
public class Demo10 {
|
||||
public static void main(String[] args) {
|
||||
//多态的写法
|
||||
Animal a = new Dog();//父类引用指向子类对象,对象的向上转型,非常安全
|
||||
a.eat();
|
||||
//a.watchDoor();//编译看左边
|
||||
|
||||
//现在a就是一只狗,我想让它看门
|
||||
Dog dog = (Dog) a;
|
||||
dog.watchDoor();
|
||||
|
||||
//现在a是一个动物,让它变成猫,抓老鼠
|
||||
Cat cat = (Cat) a;
|
||||
cat.catchMouse();
|
||||
|
||||
}
|
||||
}
|
||||
12
day10/src/com/inmind/duotai08/downcast/Dog.java
Normal file
12
day10/src/com/inmind/duotai08/downcast/Dog.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.inmind.duotai08.downcast;
|
||||
|
||||
public class Dog extends Animal{
|
||||
@Override
|
||||
public void eat() {
|
||||
System.out.println("狗吃骨头");
|
||||
}
|
||||
|
||||
public void watchDoor(){
|
||||
System.out.println("狗看门");
|
||||
}
|
||||
}
|
||||
@@ -13,12 +13,12 @@ public class Demo09 {
|
||||
|
||||
//以上代码没有多态,所以有50个子类,重复的代码就要编写或封装50次,太繁琐
|
||||
//多态写法
|
||||
Employee e1 = new Teacher();
|
||||
Employee e2 = new Assistant();
|
||||
dTWork(e1);
|
||||
dTWork(e2);
|
||||
dTWork(teacher);
|
||||
dTWork(assistant);
|
||||
Employee e1 = new Teacher();//引用数据类型向上转型
|
||||
Employee e2 = new Assistant();//引用数据类型向上转型
|
||||
dTWork(e1);//引用数据类型向上转型
|
||||
dTWork(e2);//引用数据类型向上转型
|
||||
dTWork(teacher);//引用数据类型向上转型
|
||||
dTWork(assistant);//引用数据类型向上转型
|
||||
}
|
||||
|
||||
//定义一个父类类型接收子类对象,多态的写法
|
||||
|
||||
Reference in New Issue
Block a user