同一方法可以根据发送对象的不同而采用多种不同的行为方式 一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多 多态存在的条件:
有继承关系 子类重写父类方法 父类引用指向子类:Father f = new Son(); 多态是方法的多态,属性没有多态性
public class Pet {
public void eat ( ) {
System. out. println ( "宠物吃东西" ) ;
}
}
public class Dog extends Pet {
@Override
public void eat ( ) {
System. out. println ( "狗吃狗粮" ) ;
}
public void paly ( ) {
System. out. println ( "狗玩球" ) ;
}
}
public class Main {
public static void main ( String[ ] args) {
Dog dog1 = new Dog ( ) ;
Pet dog2 = new Dog ( ) ;
Object dog3 = new Dog ( ) ;
dog1. eat ( ) ;
dog2. eat ( ) ;
dog1. paly ( ) ;
( ( Dog) dog2) . paly ( ) ;
}
}
instanceof
x instanceof y 能不能编译通过主要是看x和y之间有没有可能存在父子关系
public class Pet {
public void eat ( ) {
System. out. println ( "宠物吃东西" ) ;
}
}
public class Dog extends Pet {
}
public class Duck extends Pet {
}
public class Main {
public static void main ( String[ ] args) {
Object object = new Dog ( ) ;
System. out. println ( object instanceof Dog ) ;
System. out. println ( object instanceof Pet ) ;
System. out. println ( object instanceof Object ) ;
System. out. println ( object instanceof Duck ) ;
System. out. println ( object instanceof String ) ;
Pet pet = new Dog ( ) ;
System. out. println ( pet instanceof Dog ) ;
System. out. println ( pet instanceof Pet ) ;
System. out. println ( pet instanceof Object ) ;
System. out. println ( pet instanceof Duck ) ;
Dog dog = new Dog ( ) ;
System. out. println ( dog instanceof Dog ) ;
System. out. println ( dog instanceof Pet ) ;
System. out. println ( dog instanceof Object ) ;
}
}