1.对象转型
需要两个类之间有继承关系
class Animal{
public String name;
Animal(String name){
this.name=name;
}
}
class Cat extends Animal{
public String eyeColor;
Cat(String a, String e){
super(a);
this.eyeColor=e;
}
}
class Dog extends Animal{
public String furColor;
Dog(String a,String e){
super(a);
this.furColor=e;
}
}
Animal a = new Dog("small dog","yellow");
System.out.println(a.furColor); //error
System.out.println(a.name); //ok
System.out.println(a instance of Animal); //true
System.out.println(a instance of Dog); //true
Dog d = (Dog)a;
System.out.println(d.furColor);//ok
2.多态
1.要有继承;
2.要有重写;
3.父类引用指向子类对象;(在方法里)
class Animal {
private String name;
Animal(String name) {this.name = name;}
public void enjoy(){
System.out.println("叫声......");
}
}
class Cat extends Animal {
private String eyesColor;
Cat(String n,String c) {super(n); eyesColor = c;}
public void enjoy() {
System.out.println("猫叫声......");
}
}
class Dog extends Animal {
private String furColor;
Dog(String n,String c) {super(n); furColor = c;}
public void enjoy() {
System.out.println("狗叫声......");
}
}
class Lady {
private String name;
private Animal pet;
Lady(String name,Animal pet) {
this.name = name; this.pet = pet;
}
public void myPetEnjoy(){pet.enjoy();}
}
public class Test {
public static void main(String args[]){
Cat c = new Cat("catname","blue");
Dog d = new Dog("dogname","black");
Bird b = new Bird();
Lady l1 = new Lady("l1",c);
Lady l2 = new Lady("l2",d);
l1.myPetEnjoy();
l2.myPetEnjoy();
}
}