多态
注意事项
1 /* 2 基础班学生: 3 学习,睡觉。 4 高级班学生: 5 学习,睡觉。 6 7 可以将这两类事物进行抽取。 8 9 */ 10 11 abstract class Student 12 { 13 public abstract void study(); 14 public void sleep() 15 { 16 System.out.println("躺着睡"); 17 } 18 } 19 //将调用的单独封装,方便使用,多态子类重复使用时就不那么麻烦需要重新new一个对象,而是直接用父类来代表子类 实现子类的功能 20 class DoStudent 21 { 22 23 public void doSome(Student stu) 24 { 25 stu.study(); 26 stu.sleep(); 27 } 28 29 } 30 31 class BaseStudent extends Student 32 { 33 public void study() 34 { 35 System.out.println("base study"); 36 } 37 public void sleep() 38 { 39 System.out.println("坐着睡"); 40 } 41 } 42 43 class AdvStudent extends Student 44 { 45 public void study() 46 { 47 System.out.println(" adv study"); 48 } 49 } 50 51 52 53 54 class DuoTaiDemo3 55 { 56 public static void main(String[] args) 57 { 58 59 DoStudent ds = new DoStudent(); 60 ds.doSome(new BaseStudent()); 61 ds.doSome(new AdvStudent()); 62 63 64 // BaseStudent bs = new BaseStudent(); 65 // bs.study(); 66 // bs.sleep(); 67 // AdvStudent as = new AdvStudent(); 68 // as.study(); 69 // as.sleep(); 70 } 71 72 }
多态特点
1 //分静态和非静态就可以,静态是 左边,非静态子类方法 2 class Fu 3 { 4 static int num = 5; 5 void method1() 6 { 7 System.out.println("fu method_1"); 8 } 9 void method2() 10 { 11 System.out.println("fu method_2"); 12 } 13 static void method4() 14 { 15 System.out.println("fu method_4"); 16 } 17 } 18 19 20 class Zi extends Fu 21 { 22 static int num = 8; 23 void method1() 24 { 25 System.out.println("zi method_1"); 26 } 27 void method3() 28 { 29 System.out.println("zi method_3"); 30 } 31 32 static void method4() 33 { 34 System.out.println("zi method_4"); 35 } 36 } 37 class DuoTaiDemo4 38 { 39 public static void main(String[] args) 40 { 41 42 // Fu f = new Zi(); 43 // 44 // System.out.println(f.num); 45 // 46 // Zi z = new Zi(); 47 // System.out.println(z.num); 48 49 //f.method1(); 50 //f.method2(); 51 //f.method3();//没有,编译失败 52 53 Fu f = new Zi(); 54 System.out.println(f.num); 55 f.method4();//static看父类 56 57 Zi z = new Zi(); 58 z.method4(); 59 60 61 62 /* 63 在多态中成员函数的特点: 64 在编译时期:参阅引用型变量所属的类中是否有调用的方法。如果有,编译通过,如果没有编译失败。 65 在运行时期:参阅对象所属的类中是否有调用的方法。 66 简单总结就是:成员函数在多态调用时,编译看左边,运行看右边。 67 68 69 在多态中,成员变量的特点: 70 无论编译和运行,都参考左边(引用型变量所属的类)。 71 72 73 在多态中,静态成员函数的特点: 74 无论编译和运行,都参考做左边。 75 76 77 */ 78 79 80 // Zi z = new Zi(); 81 // z.method1(); 82 // z.method2(); 83 // z.method3(); 84 } 85 }
多态的主板示例