码迷,mamicode.com
首页 > 编程语言 > 详细

Java多态:upcast和downcast

时间:2015-06-07 18:39:43      阅读:410      评论:0      收藏:0      [点我收藏+]

标签:

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()}");
    }
}

 

Java多态:upcast和downcast

标签:

原文地址:http://www.cnblogs.com/alexkn/p/4558755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!