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();
        }
    }
    
  • 相关阅读:
    Nginx教程(三) Nginx日志管理
    Nginx教程(二) Nginx虚拟主机配置
    官方解析Cookies和Session的区别
    J2EE十三个技术规范
    J2EE十三个规范小结
    tomcat -web.xml里的内容
    tcp协议和udp协议的使用场景
    IntelliJ IDEA创建maven web项目(IDEA新手适用)
    Maven安装与配置
    X86、X64和X86_64区别
  • 原文地址:https://www.cnblogs.com/zxcoder/p/12250210.html
Copyright © 2011-2022 走看看