java多态让我觉得比较绕的就应该是向上转化跟向下转化了。
一、向上转化
class Father {private int money; public int getMoney() {return money; }public void setMoney(int money) {this.money = money; }public void printInfo() {System.out.println("This is Father");}}class Son extends Father{public void printInfo() {System.out.println("This is son");}public void playGame() {System.out.println("playGame ...");}}class Daughter extends Father{public void printInfo() {System.out.println("This is daughter");}}public class Cnv4 {public static void main (String args[]) {Father f = new Father();Son s = new Son();Daughter d = new Daughter();print(f);print(s);print(d);}public static void print(Father f) {f.printInfo();}}
向上转化:我的理解是,父类有可继承的方法A B 子类 甲中有A(覆写的) B(覆写的) C。 子类乙中有 A(覆写的) B(覆写的) D。子类丙中有 A(覆写的) B(覆写的) E。类似上上面的例子,如果共同调用父类中的函数呢?
是不是应该
public class Cnv3 {public static void main (String args[]) {Father f = new Father();Son s = new Son();Daughter d = new Daughter();print(f);print(s);print(d);}public static void print(Father f) {f.printInfo();}public static void print(Son s) {s.printInfo();}public static void print(Daughter d) {d.printInfo();}}
这样写呢?这样应该算作重载。我们使用多态就可以使用这个中向上转化,来调用父类中共有的,如果子类中覆写了,那么就去调用子类中的。是不是让代码更加整洁简单?
二、向下转化
class Father {private int money; public int getMoney() {return money; }public void setMoney(int money) {this.money = money; }public void printInfo() {System.out.println("This is Father");}public void drink() {System.out.println("drink ...");}}class Son extends Father{public void printInfo() {System.out.println("This is son");}public void playGame() {System.out.println("playGame ...");}}class Daughter extends Father{public void printInfo() {System.out.println("This is daughter");}public void dance() {System.out.println("dance ...");}}public class Cnv5 {public static void main (String args[]) {Father f = new Father();Son s = new Son();Daughter d = new Daughter();printAction(f);printAction(s);printAction(d);}public static void printAction(Father f) {if (f instanceof Son) {Son son = (Son)f;son.playGame();}else if (f instanceof Daughter) {Daughter d = (Daughter)f;d.dance();}else if (f instanceof Father) {f.drink();}}}
想要在一个函数中调用父类中没有的函数,那么使用的办法就是先向上转化然后在使用向下转化。我们在向上转化之后,再向下转化时候要判断是哪一个子类,然后才能转化,这时候我们使用的就是 instanceof .
对于这种多态方式,就是知道有这么个好用的东西就行了,需要的时候打开过来再看看该怎么用就好。知识不是非要干死脑细胞,装在脑子里才叫知识。随着年纪增大,步入社会,有了家庭,更应该采用更加有效的方式学习累积。