------- android培训、java培训、期待与您交流! ----------
多态也就是多种状态,多种形态.
class 宠物{
void 叫(){
}
}
class 狗 extends 宠物{
}
class 猫 extends 宠物{
}
狗 dod=new 狗();//要一条狗,new出来一个.
猫 cat=new 猫();
多态的前提:1.要存在继承关系, 2.要有重写多态的体现: 父类的引用指向了自己的子类对象; 父类的引用也可以接受自己的子类对象.
程序中最常见的多态的体现: 父类引用指向子类对象
宠物 cw=new 狗();
宠物 cw=new 猫();
多态存在时,成员属性与成员方法表现
Father a=new Son();
1.实例属性 a.name
编译时:查看Father中是否存在name属性
执行时:调用的是Father中的name属性
2.类属性 a.country
编译时:查看Father中是否存在country属性
执行时:调用的是Father中的country属性
3.类方法 a.method();
编译时:查看Father中是否存在method()静态方法
执行时:调用的是Father中的method()静态方法
4.实例方法 a.show();
编译时:查看Father中是否存在show()实例方法
执行时:执行的是子类Son中的show()实例方法。
总结: 1.关于属性都是查看父类中是否存在该属性,调用的也是父类中的属性 静态方法也是一样的。
2.对于实例方法来说编译时查看父类中是否有这个方法,真正执行时执行的是子类中的重写方法。
class Father
{
String name="tom"; //实例属性
static String country="zh"; //类属性
//实例方法
public void show(){
System.out.println("father类中的show");
}
//类方法
public static void method(){
System.out.println("father类中的静态方法");
}
}
class Son extends Father
{
String name="tony"; //将从父类中的继承的name属性隐藏了. 实例属性
static String country="china"; //类属性
//子类中重写的方法 实例方法
public void show(){
System.out.println("son类中的show");
}
//子类重写父类中的静态方法
public static void method(){
System.out.println("son类中的静态方法");
}
}
多态的好处: 多态的出现大大的提高了程序的扩展性.
多态的弊端: 只能使用父类的引用访问父类已有的成员.不能调用子类中所特有的成员.
多态存在时类型的转换
前提:必须存在多态
自动转换(向上转型) :父类引用指向子类对象 Father f=new Son();
强制转换(向下转型): Son son=(Son)f;
在做向下转型时会使用到一个 instanceof 关系操作符
它的作用是判断某个引用所指向的对象的类型是否是指定的类型
格式 引用(对象) instanceof 类型
它操作后得到的结果是一个boolean类型的。
instanceof只能判断有关系的操作。
使用instanceof会有一个问题,如果判断的是父类类型,它返回的也是true.
如果真正要判断一个引用所指向的对象的真实类型 通过getClass()方法去获得.
多态的练习
class Demo
{
public static void main(String[] args) {
//我们需要一个可以叫的动物
Animal a=new Pig();//new Dog(); //new Cat(); //new Pig();
a.sound(); //我们只需要知道父类中有sound方法就可以,而不需要知道具体子类中是怎样实现的。
}
}
//动物
class Animal {
void sound(){ //叫
System.out.println("动物叫....");
}
}
class Cat extends Animal {
//重写
void sound(){ //叫
System.out.println("喵喵....");
}
}
class Dog extends Animal {
//重写
void sound(){ //叫
System.out.println("汪汪....");
}
}
class Pig extends Animal {
//重写
void sound(){ //叫
System.out.println("哼哼....");
}
}
------- android培训、java培训、期待与您交流! ----------