首页 > 代码库 > Java 多态

Java 多态

Feeder feeder=new Feeder();Animal animal=new Dog();Food food=new Bon();feeder.feed(animal,food);//给狗喂肉狗骨头anmal=new Cat();foof=new Fish();feeder.feed(animal,food);给猫喂鱼

技术分享

如图把引用变量转换为子类类型,则称为向下转型,如果把引用变量装换为父类类型,则称为向上转型。在进行引用变量的类型转换时会受到各种限制。而且在通过引用变量访问他所引用的实例的静态属性。静态方法。实例属性。实例方法,以及从父类中继承的方法和属性时,Java会用不同的绑定机制。

class Base{String var="BaseVar";           //实例变量static String staticvar="StaticBaseVar"  //静态变量void metod()           //实例方法system.out.Println("Base method");}static void staticMethod()  //静态方法{syso.out.printIn("Static Base method");}}public class Sub extends Base{String var="Subvar";  static String staticVar="staticSubvar";void method()  //覆盖父类的method()方法{Sysotem.out.printIn("Static sub method");}static void staticMethod()  //隐藏父类的staticMethod()方法{system.out.printin("static sub method");}String subVar="Var only belonging to  sub";void subMethod(){System.out.pritn("Method only belonging to sub");}public static void main(String args[]){Base who=new Sub();                  //who被声明为Base类型,引用SubSystem.out.printin("who.var"+who.var);  //打印Base类的var变量System.out.printIn("who.staticVar"+wh.saticVar); //打印Base类staticVar变量who.metod();             //打印Sub实例的method()方法who.staticMethod();        //打印Base类的staticMethod();}}

技术分享

 

技术分享

 

Java 多态