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中只有方法被重写,是没有属性被重写的概念的。属性只与所指对象类型有关。 

结论:

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

Java多态--子类对象指向父类引用_第1张图片

你可能感兴趣的:(java,开发语言)