您的位置:首页 > 编程语言 > Java开发

Java多态:upcast和downcast

2015-06-07 17:26 555 查看
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()}");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: