什么是多态?简单的说就是一个引用在不同情况下的多种状态!
继承多态:
1 package com.demo.polymorphism; 2 3 /** 4 * Description:继承多态 5 * 6 * @author HackerD 7 * 8 */ 9 public class Polymorphism { 10 11 /** 12 * @param args 13 */ 14 public static void main(String[] args) { 15 Animal animal=new dog(); 16 animal.cry(); 17 18 animal=new cat(); 19 animal.cry(); 20 } 21 22 } 23 24 class Animal{ 25 public void cry() { 26 System.out.println("我不知道怎么叫!"); 27 } 28 } 29 30 class dog extends Animal{ 31 public void cry() { 32 System.out.println("小狗,汪汪叫!"); 33 } 34 } 35 36 class cat extends Animal{ 37 public void cry() { 38 System.out.println("小猫,喵喵叫!"); 39 } 40 }
接口多态:
1 package com.demo.polymorphism; 2 3 /** 4 * Description:接口多态 5 * 6 * @author HackerD 7 * 8 */ 9 public class Polymorphism2 { 10 11 /** 12 * @param args 13 */ 14 public static void main(String[] args) { 15 Usb usb = new camera(); 16 usb.start(); 17 usb.stop(); 18 19 usb = new cellphone(); 20 usb.start(); 21 usb.stop(); 22 } 23 24 } 25 26 interface Usb { 27 public void start(); 28 29 public void stop(); 30 31 } 32 33 class camera implements Usb { 34 35 @Override 36 public void start() { 37 // TODO Auto-generated method stub 38 System.out.println("我是相机,我开始工作了!"); 39 } 40 41 @Override 42 public void stop() { 43 // TODO Auto-generated method stub 44 System.out.println("我是相机,我停止工作了!"); 45 } 46 47 } 48 49 class cellphone implements Usb { 50 51 @Override 52 public void start() { 53 // TODO Auto-generated method stub 54 System.out.println("我是手机,我开始工作了!"); 55 } 56 57 @Override 58 public void stop() { 59 // TODO Auto-generated method stub 60 System.out.println("我是手机,我停止工作了!"); 61 } 62 63 }