Java多态--子类对象指向父类引用

Java面向对象的三大特性之一多态,多态的三大必要条件:

  1. 继承;
  2. 子类重写父类方法;
  3. 子类对象指向父类引用;

在子类对象指向父类引用的场景

package com.learn.blog.demo;

public class Demo1 {
    public static void main(String[] args) {
        // 子类对象指向父类引用
        Fu sub = new Sub();

        // 调用对象的方法
        sub.method();

        // 调用对象的属性
        System.out.println(sub.name);
    }


    static class Fu {
        private String name = "fu";

        static {
            System.out.println("this is fu static block");
        }

        {
            System.out.println("this is fu common block");
        }

        public Fu() {
            System.out.println("this is fu constructor");
        }

        public void method() {
            System.out.println("this is fu");
        }
    }

    static class Sub extends Fu {
        private String name = "sub";

        static {
            System.out.println("this is sub static block");
        }

        {
            System.out.println("this is sub common block");
        }

        public Sub() {
            System.out.println("this is sub constructor");
        }

        public void method() {
            System.out.println("this is sub");
        }
    }
}

上面程序执行结果为

this is fu static block
this is sub static block
this is fu common block
this is fu constructor
this is sub common block
this is sub constructor
this is sub
fu

代码分析1:

Fu sub = new Sub();

这一行的执行结果:

this is fu static block
this is sub static block
this is fu common block
this is fu constructor
this is sub common block
this is sub constructor

子类对象指向父类引用时,先执行父类,优先级别如下:

静态代码块-->普通代码块-->构造函数

所以,这行代码整体的执行流程是:

父类静态代码块-->子类静态代码块-->父类普通代码块-->父类构造函数-->子类普通代码块-->子类构造函数

代码分析2:

sub.method();

这一行的执行结果:

this is sub

父类引用调用方法,由于被子类重写了,所以真正调用的是子类里的方法。 

代码分析3:

System.out.println(sub.name);

 这一行的执行结果:

fu

Java中只有方法被重写,是没有属性被重写的概念的。属性只与所指对象类型有关。 

结论:

记忆诀窍:方法看右边,属性看左边

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值