多态
class Animal
{
}
class Cat extends Animal
{
}
class Dog extends Animal
{
}
Cat x = new Cat();
Animal x = new Cat();//一个对象,两种形态。
猫这类事物既具备着猫的形态,又具备着动物的形态。
这就是对象的多态性。
简单的说:就是一个对象对应着不同的类型。
多态在代码中的体现:
父类或者接口的引用指向其子类的对象。
多态的好处:
提高了代码的扩展性,前期定义的代码可以使用后期的内容。
多态的弊端:
前期定义的内容不能使用(调用)后期子类的特有内容。
多态的前提:
必须有关系,要么继承,要么实现。
abstract class Animal
{
abstract void eat();
}
class Cat extends Animal
{
void eat ()
{
System.out.println("吃鱼....");
}
void catchMouse()
{
System.out.println("捉老鼠....");
}
}
class Dog extends Animal
{
void eat ()
{
System.out.println("啃骨头....");
}
void guard()
{
System.out.println("看家....");
}
}
class DuoTaiDemo
{
public static void main(String[] args)
{
/*// 1.
Cat c = new Cat();
Dog d = new Dog();
Method(c);
Method(d);
*/
// 2.
/* Cat c = new Cat();
c.eat();
c.catchMouse();
Animal a = new Cat();
//当父类引用指向子类对象时,会发生一个自动类型提升。
//自动类型提升,猫对象提升为动物类型,猫的特有功能就无法使用了。
//作用是为了限制对子类特有功能的访问。
//专业讲:向上转型。
a.eat();
//如果还想用具体动物猫的特有功能。
//可以将该对象向下转型。
Cat c1 = (Cat) a;//向下转型的目的是为了使用子类中的特有方法。
//向下转型要指定以前的子类型。比如以前是猫->动物,现在还是动物->猫。否则会出错。
c1.eat();
c1.catchMouse();
//注意:对于转型,自始至终都是子类对象在做着类型的变换。
*/
// 4.
Animal a = new Cat();
Method(a);
Animal d = new Dog();
Method(d);
}
public static void Method(Animal a)//Animal d = new Dog();Animal c = new Cat();
{
a.eat();
//instanceof 用于判断对象的类型,只能用于引用数据类型.
//通常在向下转型前用于健壮性的判断.
{
Cat c = (Cat)a;
c.catchMouse();
}else if(a instanceof Dog)
{
Dog d = (Dog)a;
d.guard();
}
}
}
多态成员
Father f = new Kid();
成员变量 : 编译和运行时都看左边
成员函数(非静态):编译看左边,运行看右边.
如果左边的类中无该方法,则无法通过编译.运行时看的是右边对象中的方法.
静态函数:编译和运行都是看左边的.
其实对于静态函数,是不需要对象的,直接用类名调用即可.
class Father
{
int num = 4;
void show()
{
System.out.println("Father show");
}
static void method()
{
System.out.println("Father method");
}
}
class Kid extends Father
{
int num = 5;
void show()
{
System.out.println("Kid show");
}
static void method()
{
System.out.println("Kid method");
}
}
class DuoTaiDemo3
{
public static void main(String[] args)
{
Father f = new Kid();
System.out.println(f.num);
f.show();
f.method();
}
}