本帖最后由 linder_qzy 于 2015-3-9 22:09 编辑
多态是什么
事物存在的多种体现形态
多态的表现形式
父类的引用指向了自己子类的对象;父类的引用也可以接收自己的子类对象
多态的好处
大大提高了代码的扩展性。
多态的前提
类与类之间必须有关系,要那么继承,要么实现;方法需要完全覆盖。
多态的弊端
提高了扩展性,但是只能用父类的引用去访问父类的成员。
- abstract class Animal
- {
- public abstract void eat();
- }
- class Cat extends Animal
- {
- public void eat(){
- System.out.println("吃鱼");
- }
- public void catchMouse(){
- System.out.println("抓老鼠");
- }
- }
- class Dog extends Animal
- {
- public void eat(){
- System.out.println("吃骨头");
- }
- public void catchHome(){
- System.out.println("看家");
- }
- }
- class Demo01_DuoTai
- {
- public static void main(String[] args)
- {
- //多态的表现形式:父类的引用指向了自己子类的对象;父类的引用也可以接收自己的子类对象
- function(new Cat());
- function(new Dog());
- function(new Pig());
- /*
- 输出结果
- 吃鱼
- 吃骨头
- */
- }
- public static void function(Animal a){
- a.eat();
- }
- }
复制代码
介绍一个关键字 instanceof
instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例
- abstract class Ainimal {
-
- abstract void eat();
- }
- class Cat extends Ainimal{
- public void eat()
- {
- System.out.println("猫吃鱼!!");
- }
- public void catchMouse()
- {
- System.out.println("猫抓老鼠!!");
- }
- }
- class Dog extends Ainimal{
- public void eat()
- {
- System.out.println("狗吃肉!!");
- }
- public void catchHome()
- {
- System.out.println("狗看家!!");
- }
- }
- public class Demo0309
- {
- public static void main(String[] args)
- {
- function(new Cat());
- function(new Dog());
- }
- public static void function(Ainimal a)
- {
- a.eat();
- //判断a是否是Cat的实例
- if(a instanceof Cat)
- {
- Cat c = (Cat)a;
- c.catchMouse();
- }
- if(a instanceof Dog)
- {
- Dog d = (Dog)a;
- d.catchHome();
- }
- }
- }
- /*
- * 输出结果
- * 猫吃鱼!!
- 猫抓老鼠!!
- 狗吃肉!!
- 狗看家!!
- */
复制代码 |
|