多态:某一类事物的多种存在形态
如:动物中的猫和狗
猫对象对象的类型是猫类型,即 cat c1= new cat()
但同时猫也是动物中的一种,也可以把猫成为动物,即 animal c1= new cat()
多态提现:父类的引用指向了自己子类对象。
父类的引用也可以接受自己的子类对象。
多态前提:1.必须是雷和类之前有关系,要么继承,要么实现。
2.存在复写
多态好处:大大提高了程序的扩展性
多态弊端:只能使用父类的引用访问父类的成员
abstract class animal
{
abstract void eat();
}
class cat extends animal
{
void eat()
{
System.out.println("cat eat");
}
void say()
{
System.out.println("miu,miu");
}
}
class dog extends animal
{
void eat()
{
System.out.println("dog eat");
}
void say()
{
System.out.println("wang,wang");
}
}
class DuoDemo1
{
public static void main(String[] args)
{
fuc(new cat());
fuc(new dog());
}
static void fuc(animal a)// 多态的表现animal a=new cat();模板设计思想,把不确定的暴露出来
{
a.eat();
}
}
向上转型和向下转型:
abstract class animal
{
abstract void eat();
}
class animal
{
void eat(){};
}
class cat extends animal
{
void eat()
{
System.out.println("cat eat");
}
void say()
{
System.out.println("miu,miu");
}
}
class dog extends animal
{
void eat()
{
System.out.println("dog eat");
}
void say()
{
System.out.println("wang,wang");
}
}
class DuoDemo1
{
public static void main(String[] args)
{
animal a1=new cat();//多态表现,也是向上转型
//animal a2=new animal() 当animal为非抽象类,不能强制向下转型
/*千万不要出现把父类对象转换成子类类型。*/
a1.eat();
cat cl=(cat)a1;//如果子类想调用自己的特有方法,需要强制将父类的引用转换为子类类型。也叫向下转型。
cl.say();
}
}
多态中成员特点:
1) 在多态中成员函数的特点:
在编译时期:参阅引用型变量所属的类中是否有调用的方法。如果有,编译通过,如果没有编译失败。
在运行时期:参阅对象所属的类中是否有调用的方法。
简单总结就是:成员函数在多态调用时,编译看左边,运行看右边。
2)在多态中,成员变量的特点:
无论编译和运行,都参考左边(引用型变量所属的类)。
3)在多态中,静态成员函数的特点:
无论编译和运行,都参考做左边。
class Fu
{
static int num = 6;
void method1()
{
System.out.println("fu method_1");
}
void method2()
{
System.out.println("fu method_2");
}
static void method4()
{
System.out.println("fu method_4");
}
}
class Zi extends Fu
{
static int num = 8;
void method1()
{
System.out.println("zi method_1");
}
void method3()
{
System.out.println("zi method_3");
}
static void method4()
{
System.out.println("zi method_4");
}
}
class DuoTaiDemo4
{
public static void main(String[] args)
{
Fu f = new Zi();
System.out.println(f.num);
f.method1();
f.method2();//多态中的成员函数运行时看右边,尽管子类没有method2方法,但是他继承了父类的method2方法,因此可以运行
//f.method3();//编译时后报错,因为多态中的成员函数编译时看左边,也就是看父类,父类没有method3方法,因此会报错
f.method4();
Zi z = new Zi();
z.method4();
}
}