java-对象的多态

多态在面向对象中是一个非常重要的概念,对象的多态主要表现在两个方面:

  • 方法的重载的覆写
  • 对象的多态性

对象的多态性主要分为以下两种类型:

  • 向上转型:子类对象-父类对象
  • 向下转型:父类对象-子类对象

对象向上转型,程序会自动完成。向下转型,必须明确指定要转型的子类类型。格式如下:
对象向上转型:父类 父类对象 = 子类实例;
对象向下转型:子类 子类对象 = (子类)父类实例;
对象向上转型的案例:
定义父类:

public class Father {

    public void fun1(){
        System.out.println("father`s method fun1");
    }
    public void fun2(){
        System.out.println("father's method fun2");
    }
}

定义子类

public class Son extends Father {

    @Override
    public void fun1() {
        System.out.println("son's method fun1 ");
    }
    public void fun3(){
        System.out.println("son's method fun3");
    }
}

测试向上转型

    @Test
    public void test() {
        Son son = new Son();
        Father father = son;
        father.fun1();
    }

test result:

son’s method fun1
分析:
虽然调用的father的fun1方法,但是实际上调用的是子类的fun1方法。也就是说,当对象发生了向上转型之后,调用的一定是被子类覆写的方法。但是father是无法调用son类中定义fun3方法的。如果想调fun3方法,需要有子类的实例进行调用。

对象向下转型:
还是使用上面的案例进行测试:

    @Test
    public void test2() {
        Father father = new Son(); //向上转型
        Son son = (Son) father;  //向下转型
        son.fun1();
        son.fun2();
        son.fun3();
    }

result:

son’s method fun1
father’s method fun2
son’s method fun3

需要注意的一点是:在向下转型之前必须先向上转型。

发布了22 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_19408473/article/details/71194358