多态:多种形态,即对象的多态性。
//构建一个抽象类animal,定义一个抽象方法eat abstract class animal{ abstract void eat(); } //子类bird继承父类 class bird extends animal{ //覆盖eat方法 void eat(){ System.out.println("warm"); } } public class PolyDemo{ public static void main(String args[]){ //实例化bird,此时会出现一个问题,当new有多个bird对象时,需要依次调用eat方法,代码的冗余性较大 //可以构建一个method方法,需要时调用此方法即可 bird b1 = new bird(); bird b2 = new bird(); bird b3 = new bird(); //b1.eat(); //b2.eat(); //b3.eat(); method(b1); method(b2); method(b3); } public static void method(bird b){ b.eat(); } }注:
但是此时会有一个问题,如果不是bird类调用eat方法呢,如果是dog,cat或者其他具有eat方法的呢,如果还是使用method方法,此时代码仍旧冗余这里可以使用多态的思想,eat属于这些类的共有方法,我们可以将父类animal作为method中的参数,使用父类调用eat方法,这样就提高了代码的扩展性。 //构建一个抽象类animal,定义一个抽象方法eat abstract class animal{ abstract void eat(); } //子类bird继承父类 class bird extends animal{ void eat(){ System.out.println("warm"); } } //另一个子类 class cat extends animal{ void eat(){ System.out.println("fish"); } } public class PolyDemo{ public static void main(String args[]){ //实例化bird,此时会出现一个问题,当new有多个bird对象时,需要 依次调用eat方法,代码的冗余性较大 //可以构建一个method方法,需要时调用此方法即可 //使用多态的思想 animal a1 = new bird(); animal a2 = new bird(); animal a3 = new cat(); animal a4 = new cat(); method(a1); method(a2); method(a3); method(a4); //bird b1 = new bird(); //bird b2 = new bird(); //bird b3 = new bird(); //b1.eat(); //b2.eat(); //b3.eat(); //method(b1); //method(b2); //method(b3); } public static void method(animal a){ a.eat(); } } 多态在程序中的体现:父类的引用或者接口的引用指向了子类的对象好处:多态提高了代码的拓展性弊端:不能使用子类的特有方法,只能使用子类的共有方法多态的前提: 必须有关系,继承或者实现。通常有覆盖。向上转型好处及弊端:
好处是隐藏了子类型,提高了代码的扩展性。弊端是只能使用父类中的功能,不能使用子类中的特有功能,功能被限定了。如果不需要面对子类型,通过提高扩展性或者使用父类的功能即可完成操作,就使用向上转型。向下转型好处及弊端:
好处是可以使用子类的特有功能弊端是面向具体的子类型,向下转型有风险。容易发生ClassCastException,即转换类型和对象类型不匹配就会发生 //Cat中没有lookhome方法,Cat类型和Dog类型不匹配,但编译可以通过 Animal a = new Cat();//ClassCastException Dog d = (Dog)a; d.lookhome(); 想要确定安全,需要进行判断,判断一个对象是否匹配某一个类型使用关键字instanceof 即 对象 instanceof 类型 Animal a = new Cat();//ClassCastException //判断对象是否匹配类型 if(!(a instanceof Dog)) throw new ClassCastException(a.getClass().getName()+"类型不匹配"); //向下转型 //可以在使用向上转型后将对象向下转型,这样可以不用再实例化一个对象 Dog d = (Dog)a; d.lookhome(); 当需要用到子类型的特有方法时使用向下转型,但一定要判断