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()}"); } }
时间: 2024-11-05 21:56:39