Java多态之Father f=new Son();

栏目: IT技术 · 发布时间: 6年前

内容简介:成员变量静态方法看左边,非静态方法编译看左边,运行看右边。

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

  • 左边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();
    }
}

以上所述就是小编给大家介绍的《Java多态之Father f=new Son();》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms Illuminated (Part 2)

Algorithms Illuminated (Part 2)

Tim Roughgarden / Soundlikeyourself Publishing, LLC / 2018-8-5 / USD 17.99

Algorithms are the heart and soul of computer science. Their applications range from network routing and computational genomics to public-key cryptography and machine learning. Studying algorithms can......一起来看看 《Algorithms Illuminated (Part 2)》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具