Why use up transformation instead of directly creating subclass objects?
•
Java
Example 1
public class Animal {
public void sleep() {
System.out.println("小动物在睡觉");
}
public static void doSleep(Animal animal) {
// 此时的参数是父类对象,但是实际调用时传递的是子类对象,就是向上转型。
animal.sleep();
}
public static void main(String[] args) {
animal.doSleep(new Cat());
animal.doSleep(new Dog());
}
}
public class Cat extends Animal {
@Override
public void sleep() {
System.out.println("猫正在睡觉");
}
}
public class Dog extends Animal {
@Override
public void sleep() {
System.out.println("狗正在睡觉");
}
}
The cat is sleeping and the dog is sleeping
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
