父类的引用指向子类的对象,但是cat属于父类,所以Animal cat = new Cat()的cat对象,不能调用子类多出来的内容,比如这里的enjoy方法 (向上转型)
public class Helloworld1 {
public static void main(String args[]) {
Animal cat = new Cat();
cat.name = "tom";
cat.sleep();
}
}
class Animal {
String name;
public void sleep() {
System.out.println(name+" is sleepping");
}
}
class Cat extends Animal {
String furColor;
public void enjoy() {
System.out.println(name+" enjoy");
}
}
....................................................................................................................................
向下转型:强制类型转换。
public class Helloworld1 {
public static void main(String args[]) {
Cat cat = new Cat();
cat.name = "tom";
Cat a = (Cat)cat; //向下转型,使得cat对象转换为Cat类,这样他才能调用子类多出来的内容
a.catchMouse();
}
}
class Animal {
String name;
public void sleep() {
System.out.println(name+" is sleepping");
}
}
class Cat extends Animal {
String furColor;
public void catchMouse() {
System.out.println("catch");
}
}