多态:可以理解为事物存在的多种体现形态。
例如:人:男人,女人;
动物:猫,狗
猫 x = new 猫();
动物 x = new 猫();
从以下几个方面介绍多态:
以动物:猫,狗,猪为例说之
abstract class Animal { public abstract void eat(); } class Cat extends Animal { public void eat() { System.out.println("吃鱼"); } public void catchMouse() { System.out.println("抓老鼠"); } } class Dog extends Animal { public void eat() { System.out.println("吃骨头"); } public void KanJia() { System.out.println("看家"); } } class Pig extends Animal { public void eat() { System.out.println("饲料"); } public void gongDi() { System.out.println("拱地"); } } //----------------------------------------------------------- public class PolDemo { public static void main(String[] args) { // Cat c = new Cat(); // c.eat(); // // Dog d = new Dog(); // d.eat(); // Cat c = new Cat(); // function(c); // // function(new Dog()); // // function(new Pig()); // Animal c = new Cat(); // c.eat(); Animal a = new Cat();//类型提升。向上转型 a.eat(); //如果想要调用猫的特有方法时,如何操作? //强制将父类的引用转成子类类型,向下转型 Cat c = (Cat)a; c.catchMouse(); /* * 千万不要出现这样的操作,就是将父类对象转成子类类型 * 我们能转换的是父类引用指向了自己的子类对象时,该引用可以被提升,也可以被强制转换 * 多态自始至终都是子类对象在做着变化 * Animal a = new Animal(); * Cat c = (Cat)a; * */ // function(new Cat()); // function(new Dog()); // function(new Pig()); } public static void function(Animal a) { //Animal a = new Cat(); a.eat(); // a.catchMouse(); /*if(a instanceof Animal) { System.out.println("hello"); } else*/ if(a instanceof Cat) { Cat c = (Cat)a; c.catchMouse(); } else if(a instanceof Dog) { Dog d = (Dog)a; d.KanJia(); } } /* public static void function(Cat c) { //Cat c = new Cat(); c.eat(); } public static void function(Dog d) { d.eat(); } public static void function(Pig p) { p.eat(); } */ }
以下例说明多态的应用:
基础班学生:学习,睡觉
高级班学生:学习,睡觉
可以将这两类事物进行抽取。
代码如下:
abstract class Student { public abstract void study(); public void sleep() { System.out.println("躺着睡"); } } //工具类 class DoStudent { public void doSomething(Student s) { s.study(); s.sleep(); } } //-------------------------------------------------------------- class BaseStudent extends Student { public void study() { System.out.println("base study"); } public void sleep() { System.out.println("坐着睡"); } } class AdvStudent extends Student { public void study() { System.out.println("adv study"); } } public class DuoTaiDemo { public static void main(String[] args) { DoStudent ds = new DoStudent(); ds.doSomething(new BaseStudent()); ds.doSomething(new AdvStudent()); // BaseStudent bs = new BaseStudent(); // bs.study(); // bs.sleep(); // AdvStudent as = new AdvStudent(); // as.study(); // as.sleep(); } }
原文:http://www.cnblogs.com/yerenyuan/p/5205131.html