java中的接口
本文主要讲述java的接口,以其相关细节。
老韩接口的介绍:
老韩接口的细节:
老韩继承类vs接口实现
老韩接口的多态性
1)接口的多态性示意图,如下图所示:
示例代码如下:
USB接口:
1 interface USBInterface { 2 public void start(); 3 public void end(); 4 }
Phone类:
1 public class Phone implements USBInterface{ 2 @Override 3 public void start() { 4 System.out.println("phone开始工作"); 5 } 6 7 @Override 8 public void end() { 9 System.out.println("phone停止工作"); 10 } 11 }
Camera类:
1 public class Camera implements USBInterface { 2 @Override 3 public void start() { 4 System.out.println("camera开始工作"); 5 } 6 7 @Override 8 public void end() { 9 System.out.println("camera停止工作"); 10 } 11 }
Computer类:
1 public class Computer { 2 public void work(USBInterface usbInterface){ 3 usbInterface.start(); 4 usbInterface.end(); 5 } 6 }
Test类:
1 public class InterfaceTest { 2 public static void main(String[] args) { 3 Computer computer = new Computer(); 4 Camera camera = new Camera(); 5 Phone phone = new Phone(); 6 7 // 体现了接口的多态性 8 computer.work(camera); 9 computer.work(phone); 10 } 11 }
运行结果如下:
2)接口的多态数组,示例代码如下:
1 public class InterfaceExercise { 2 public static void main(String[] args) { 3 4 USB[] usb_arr = new USB[2]; 5 6 usb_arr[0] = new Phone_(); 7 usb_arr[1] = new Camera_(); 8 9 InterfacePloyArr(usb_arr); 10 11 12 } 13 public static void InterfacePloyArr(USB[] usb_arr){ 14 for(int i = 0;i<usb_arr.length;i++){ 15 usb_arr[i].start();// 动态绑定 16 if(usb_arr[i] instanceof Phone_){ 17 // ((phone) usb_arr[i]).call(); 18 Phone_ p = (Phone_) usb_arr[i]; 19 p.call(); 20 } 21 if(usb_arr[i] instanceof Camera_){ 22 // ((camera) usb_arr[i]).photo(); 23 Camera_ c = (Camera_) usb_arr[i]; 24 c.photo(); 25 } 26 usb_arr[i].end(); // 动态绑定 27 } 28 } 29 } 30 31 interface USB { 32 void start(); // public static 33 void end(); 34 } 35 class Phone_ implements USB{ 36 @Override 37 public void start() { 38 System.out.println("phone接入usb接口"); 39 } 40 41 @Override 42 public void end() { 43 System.out.println("phone断开usb接口"); 44 } 45 46 public void call(){ 47 System.out.println("phone打电话"); 48 } 49 } 50 51 class Camera_ implements USB{ 52 @Override 53 public void start() { 54 System.out.println("camera接入usb接口"); 55 } 56 57 @Override 58 public void end() { 59 System.out.println("camera断开usb接口"); 60 } 61 62 public void photo(){ 63 System.out.println("camera摄影"); 64 } 65 }
运行结果如下:
接口的多态数组与类的多态数组非常相似。