1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
package 面向对象核心;
public class TestPolyf { public static void main(String[] args) { Animal a = new Animal(); Animal d_ = new Dog(); Animal c_ = new Cat(); Dog d = new Dog(); Cat c = new Cat(); d_.x = 1; Dog _d = (Dog)d_; _d.y = 1; Dog _d_ = (Dog)c_; _d_.y = 1; animalCry(a); animalCry(d_); animalCry(c_); animalCry(d); animalCry(c); } static void animalCry(Animal a) { a.shout(); } }
class Animal{ int x; public void shout() { System.out.println("Animal shout!"); } }
class Dog extends Animal{ int y; public void shout() { System.out.println("Dog shout!"); } }
class Cat extends Animal{ int z; public void shout() { System.out.println("Cat shout!"); } }
|