zoukankan      html  css  js  c++  java
  • Java多态之Father f=new Son();

    成员变量静态方法看左边,非静态方法编译看左边,运行看右边。

    • 左边Father f其实是定义了一个Father类的对象,而右边new Son()可以只理解为是一个重写了Father类方法的对象。
    • 因此,f的成员变量,静态方法都是Father类的,而只有被重写的方法才是调用Son类的。
    • 所以编译看左边指的是如果调用Son类的特有方法的话会编译错误,因为这个被重写的Father类里并没有这个Son类的特有方法。
    class Father{
        int a=1;
        static int b=2;
        void say(){
            System.out.println("I am father");
        }
    
        void ffun(){
            System.out.println("father's function");
        }
    
        static void fun(){
            System.out.println("static father");
        }
    }
    
    class Son extends Father{
        int a=3;
        static int b=4;
        void say(){
            System.out.println("I am son");
        }
    
        void sfun(){
            System.out.println("son's function");
        }
    
        static void fun(){
            System.out.println("static son");
        }
    }
    
    public class Polymorphism1 {
        public static void main(String[] args) {
            Father a=new Son();
            a.say();
            a.ffun();
            System.out.println(a.a);
            Father b=new Father();
            b.say();
            b.ffun();
            System.out.println(b.a);
            Son c=new Son();
            c.say();
            c.sfun();
            System.out.println(c.a);
            System.out.println(Father.b);
            System.out.println(Son.b);
            Father.fun();
            Son.fun();
        }
    }
    
  • 相关阅读:
    react-redux
    Vue中常用的UI框架
    vue中router与route的区别
    H5新增input属性
    H5新增的input类型
    菜鸡对作用域链的理解
    自己对路由的一些理解
    浏览器缓存
    黄瓜的不定期更新面试题
    ajax封装
  • 原文地址:https://www.cnblogs.com/zxcoder/p/12250210.html
Copyright © 2011-2022 走看看