多态:对象执行某个行为方法式表现出不同的形态。
多态分两种:静态多态(编译多态)通过方法重载来实现,动态多态(运行多态),通过重写来实现。
动态多态一般通过父类的引用,指向子类的实例来实现。实例调用的时候,调的是子类的方法。
练习:
public class Che { //父类Che protected String cheming; private String leixing; private String dangwei; public Che(String cheming){ //重载 参数符合会运行 this.cheming = cheming; } public Che(String cheming,String leixing,String dangwei){ //重载 参数符合会运行 this.cheming = cheming; this.leixing = leixing; this.dangwei = dangwei; } public void shache(){ System.out.println(cheming+"z"); } public void jiasu(){ System.out.println(cheming+"s"); } public void qidong(){ System.out.println(cheming+"h"); } }
public class Byd extends Che { //子类继承Che public Byd(String cheming){ super(cheming); } public Byd(String cheming,String leixing,String dangwei){ super(cheming,leixing,leixing); } public void shache(){ System.out.println(cheming+"正在刹车"+"1"); } public void jiasu(){ System.out.println(cheming+"正在加速"+"1"); } public void qidong(){ System.out.println(cheming+"正在启动"+"1"); } }
public class Jipu extends Che { //子类也是继承Che public Jipu(String cheming) { super(cheming); } public Jipu(String cheming,String leixing,String dangwei){ super(cheming,leixing,dangwei); } public void qidong(){ System.out.println(cheming+"正在启动"+"2"); } public void jiasu(){ System.out.println(cheming+"加速"+"2"); } public void shache(){ System.out.println(cheming+"正在刹车"+"2"); } }
public class Siji { //定义一个类Siji方法来调用父类方法 public void jiashi(Che c){ //引用父类Che实例化子类 c.qidong(); c.jiasu(); c.shache(); } }
public static void main(String[] args) { Che b = new Byd("比亚迪"); //实参 Che j = new Jipu("吉普"); //实参 Siji s = new Siji(); s.jiashi(b); //再用jiashi()方法调用Byd
s.jiashi(j); //再用jiashi()方法调用Jipu 实现运行多态(动态多态) } }