classDemo2_polymorphic{ publicstaticvoidmain(String[] args){ Father f = new Son(); //父类引用指向子类对象 System.out.println(f.num); //10 Son s = new Son(); System.out.println(s.num); //20 } }
classFather{ int num = 10; }
classSonextendsFather{ int num = 20; }
成员方法
编译看左边(父类),运行看右边(子类)。也称作动态绑定。
classDemo2_polymorphic{ publicstaticvoidmain(String[] args){ Father f = new Son(); //编译时先看Father类有无print方法,若无则编译不通过 f.print(); //son,运行时运行子类的print方法,输出son } }
classFather{ int num = 10; publicvoidprint(){ System.out.println("father"); } }
classSonextendsFather{ int num = 20; publicvoidprint(){ System.out.println("son"); } }
静态方法
编译看左边(父类),运行看左边(父类)。
classDemo2_polymorphic{ publicstaticvoidmain(String[] args){ Father f = new Son(); f.method(); //输出son static method,相当于Father.method() } }
classFather{ int num = 10; publicvoidprint(){ System.out.println("father"); } publicstaticvoidmethod(){ System.out.println("father static method"); } }
classSonextendsFather{ int num = 20; publicvoidprint(){ System.out.println("son"); } publicstaticvoidmethod(){ System.out.println("son static method"); } }
注意:
静态方法和类相关,算不上重写,所以访问的还是左边。
只有非静态的成员方法,编译看左边,运行看右边。
向上转型和向下转型
向上转型:父类引用指向子类对象。
向下转型:将已经向上转型的对象强制转换为子类的类型。
classDemo3_Superman{ publicstaticvoidmain(String[] args){ Person p = new Superman(); //父类引用指向子类对象,就是向上转型 System.out.println(p.name); //John p.talkBusiness(); //谈生意 //p.fly(); //报错,Person类没有fly方法 Superman sm = (Superman)p; //向下转型 sm.fly(); //飞出去救人 } }
classPerson{ String name = "John"; publicvoidtalkBusiness(){ System.out.println("谈生意"); } }
classDemo1_Interface{ publicstaticvoidmain(String[] args){ //Inter i = new Inter; //出错,接口不能实例化 Inter i = new Demo(); //父类引用指向子类对象 i.print(); //print } }