Java多态:upcast和downcast
发布日期:2021-08-18 00:51:42 浏览次数:2 分类:技术文章

本文共 1153 字,大约阅读时间需要 3 分钟。

upcast例:

public class Test{    public static void main(String[] args)    {         Cup aCup = new BrokenCup();        aCup.addWater(10); // method binding    }}class Cup {    public void addWater(int w)     {        this.water = this.water + w;    }    public void drinkWater(int w)    {        this.water = this.water - w;    }    private int water = 0;}class BrokenCup extends Cup{    public void addWater(int w)     {        System.out.println("shit, broken cup");    }    public void drinkWater(int w)    {        System.out.println("om...num..., no water inside");    }}

 

downcast例:

public class TestJavaDemo{    public static void main(String[] args) {        Person p=new Student();        Student s=(Student)p;        s.fun1();        s.fun2();    }}class Person{    public void fun1(){        System.out.println("1.Person{fun1()}");    }    public void fun2(){        System.out.println("2.Person{fun2()}");    }}class Student extends Person{    public void fun1(){        System.out.println("3.Student{fun1()}");    }    public void fun3(){        System.out.println("4.Student{fun3()}");    }}

 

转载于:https://www.cnblogs.com/alexkn/p/4558755.html

转载地址:https://blog.csdn.net/weixin_30872733/article/details/99307219 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:AndroidTest工程的自定义gradle task
下一篇:XNU内核案例(一)BSD系统调用fork的详细分析

发表评论

最新留言

不错!
[***.144.177.141]2024年03月29日 11时32分03秒