第四章 面向对象-多态
定义: 某一类事物的多种存在形态。 猫 x = new 猫( ); 动物 x = new 猫( ); //一个对象,两种形态。 猫这类事物即具备着猫的形态,有具备着动物的形态,这就是对象的多态性。 多态在代码中的体现: 父类或者接口的引用指向其子类对象。实现:
abstract Animal{
abstract eat ( ) ;
}
class Dog extends Animal {
void eat ( ) {
System. out. print ( "啃骨头" ) ;
}
void lookHome ( ) {
System. out, print ( "看家" ) ;
}
}
class Cat extends Animal {
void eat ( ) {
System. out. print ( "吃鱼" ) ;
}
void catchMouse ( ) {
System. out, print ( "抓老鼠" ) ;
}
}
class Demo {
public static void main ( String[ ] args) {
Cat c= new Cat ( ) ;
Dog d= new Dog ( ) ;
method ( c) ;
method ( d) ;
}
public static void method ( Animal a) {
a. eat ( ) ;
}
}
多态的好处: 提高了代码的扩展性。多态的弊端: 前期定义的内容不能使用后期子类的特有内容。多态的前提: 1.必须有关系,继承、实现。 2.必须覆盖。类型转换:
abstract Animal{
abstract eat ( ) ;
}
class Dog extends Animal {
void eat ( ) {
System. out. print ( "啃骨头" ) ;
}
void lookHome ( ) {
System. out, print ( "看家" ) ;
}
}
class Cat extends Animal {
void eat ( ) {
System. out. print ( "吃鱼" ) ;
}
void catchMouse ( ) {
System. out, print ( "抓老鼠" ) ;
}
}
class Demo {
public static void main ( String[ ] args) {
Animal a= new Cat ( ) ;
a. eat ( ) ;
Cat c= ( Cat) a;
c. catchMouse ( ) ;
}
abstract Animal{
abstract eat ( ) ;
}
class Dog extends Animal {
void eat ( ) {
System. out. print ( "啃骨头" ) ;
}
void lookHome ( ) {
System. out, print ( "看家" ) ;
}
}
class Cat extends Animal {
void eat ( ) {
System. out. print ( "吃鱼" ) ;
}
void catchMouse ( ) {
System. out, print ( "抓老鼠" ) ;
}
}
class Demo {
public static void main ( String[ ] args) {
Cat c= new Cat ( ) ;
method ( new Dog ( ) ) ;
}
public static void method ( Animal a) {
a. eat ( ) ;
if ( a instanceof Cat ) {
Cat c= ( Cat) a;
a. catchMouse ( ) ;
} else if ( a instanceof Dog ) {
Dog d= ( Dog) a;
d. lookHome ( ) ;
}
}
多态的特点: 成员函数: 1.编译时:要查看引用变量所属的类中是否有所调用成员函数, 有,编译通过,没有,编译失败。。 2.运行时:要查看对象所属的类中是否有所调用成员函数,有,编译通过,没有,编译失败。。 编译看左边,运行看右边。 成员变量: 参考引用变量所属的类中是否有调用的成员变量,有,编译通过,没有,编译失败。编译和运行都参考等号左边。静态函数: 编译和运行都看左边,因为静态方法用对象没有意义,可以直接用类名调用。