1 public class Polymorphism { 2 3 4 /** 5 * @param args 6 */ 7 public static void main(String[] args) { 8 9 Human personA = new man(); 10 // personA.sleep(); 11 // personA.eat(); 12 System.out.println("***********************************************"); 13 man personB = new man(); 14 // personB.write(); 15 // personB.eat(); 16 System.out.println("***********************************************"); 17 woman personC = new woman(); 18 // personC.eat(); 19 // personC.cook(); 20 // personC.speak(); 21 System.out.println("***********************************************"); 22 } 23 24 } 25 26 abstract class Human{ 27 int i=0; 28 static{ 29 System.out.println("This is Human static block"); 30 } 31 public Human(){ 32 System.out.println("This human constructor"); 33 fun(); 34 } 35 public void eat(){ 36 System.out.println("human eat"+1); 37 } 38 public void speak(){ 39 System.out.println("human hello"); 40 } 41 public abstract void sleep(); 42 public void fun(){ 43 System.out.println("This human fun"); 44 } 45 } 46 class man extends Human implements writer{ 47 int i = 10000; 48 static{ 49 System.out.println("This is man static block"); 50 } 51 public man(){ 52 System.out.println("This man constructor"); 53 fun(); 54 } 55 public void work() { 56 System.out.println("man is working"); 57 } 58 59 @Override 60 public void sleep() { 61 System.out.println("man sleep"); 62 63 } 64 65 public void speak() { 66 System.out.println("man is speaking"); 67 } 68 69 @Override 70 public void write() { 71 72 System.out.println("man is writing"); 73 74 } 75 76 public void eat(){ 77 System.out.println("man eat"+i); 78 } 79 80 @Override 81 public void think() { 82 83 System.out.println("man is thinking"); 84 } 85 public void fun(){ 86 System.out.println("This man fun"); 87 } 88 } 89 class woman extends Human{ 90 91 static{ 92 System.out.println("This is woman static block"); 93 } 94 95 public woman(){ 96 System.out.println("This is woman constructor"); 97 fun(); 98 } 99 public void fun(){ 100 System.out.println("This woman fun"); 101 } 102 103 @Override 104 public void sleep() { 105 System.out.println("woman sleep"); 106 } 107 108 public void cook(){ 109 System.out.println("woman is cooking"); 110 } 111 112 public void speak(){ 113 System.out.println("woman is speaking"); 114 } 115 } 116 117 interface writer{ 118 int num = 1; 119 public void write(); 120 public void think(); 121 }
这段代码一共描述了三种情况:1.子类的引用指向子类的对象;2.父类的引用指向子类的对象。3.父类和子类中的静态块执行的顺序。
一、子类的引用指向子类的对象时,先运行父类的构造方法,然后运行子类的构造方法。如果有静态块,则先运行父类中的静态块,然后运行子类中的静态块。然后运行父类子类的构造方法。
二、父类的引用指向子类的对象时,构造方法及静态块的运行顺序同上。引用可以调用父类中的方法,此时相当于将子类隐式的强制类型转换为父类对象。
三、静态块及静态变量均只加载一次,加载到内存的静态区中。
四、构造方法中调用某一方法,采取就近原则,若子类中有则调用子类的方法,若子类中无则向上查询。