Java语言中类的Encapsulation、inherit、polymorphic三大护法很重要,其中polymophic更是不得了,他会移花接木神功,老师说多态可概括为一句话,八个字:“相同代码,不同含义”,相信此八字心法会让很多菜鸟功力大增,废话不说啦,千言万语汇成一句话:学会此法,少写无数代码!
下面我给大家写个例子,领略一下此强大心法!
如果我们不写下面Test()方法,那我们在main ()方法中就要多写很多代码,在main()方法中多写的代码我用‘//’注释掉。
package cn.edu.hurst.homework;
public class JavaDemo {
public static void main(String[]args) {
Test.show(new Father()); //用Father中的Say()
Test.show(new Son()); //调用Son中的Say()
Test.show(new Grandfather()); //用Grandfather中的Say()
//如果没有Test()方法我将多写如下代码,子类越多写的代码也就越多。
//向下转型调用子类方法:
//Grandfather gf ;
//gf = new Father();
//gf.Say();
//gf = new Son();
//gf.Say();
//想要掉用Grandfather中的Say方法有两种方式;
//1、gf = new Grandfather();
// gf.Say();
//2、向上转型:gf = new Father();或是实例化成Son, 如:gf = new Son();
gf = (Grandfather)gf;
}
}
class Grandfather {
int age = 100;
String name = "爷爷";
public void Say() {
System.out.println("My name is "+name+", My age is "+age);
}
}
class Father extends Grandfather {
int age = 60;
String name = "爸爸";
public void Say() {
System.out.println("My name is "+name+", My age is "+age);
}
}
class Son extends Father {
int age = 30;
String name = "儿子";
public void Say() {
System.out.println("My name is "+name+", My age is "+age);
}
}
class Test {
public static void show(Grandfather grandfather) {
grandfather.Say();
}
}