1 /* 2 长城牌电视机 3 联想奔月5008PC机 4 */ 5 6 7 package st; 8 //接口回调实例 9 interface ShowMessage 10 { 11 void 显示商标 (String s); 12 } 13 class TV implements ShowMessage 14 { 15 public void 显示商标(String s) 16 { 17 System.out.println(s); 18 } 19 } 20 class PC implements ShowMessage 21 { 22 public void 显示商标 (String s) 23 { 24 System.out.println(s); 25 } 26 } 27 public class example_1 28 { 29 public static void main(String args[]) 30 { 31 ShowMessage sm; //声明接口变量 32 sm=new TV(); //接口变量中存放对象的引用 33 sm.显示商标("长城牌电视机"); //接口回调 34 sm=new PC(); 35 sm.显示商标("联想奔月5008PC机"); 36 } 37 }
1 /* 2 * 对于接口理解的一个列子 3 * 详情请关注龚细军(Gxjun)的博客 4 * */ 5 package st; 6 7 abstract class Motorvehicles 8 { 9 abstract void brake(); 10 } 11 // 接口1 12 interface ControlTemperature 13 { 14 void ControlAirTemperature(); 15 } 16 //接口2 17 interface MonenyFare 18 { 19 void Charge(); 20 } 21 class Bus extends Motorvehicles implements MonenyFare 22 { 23 void brake() 24 { 25 System.out.println("公交车来啦!,嘟嘟"); 26 } 27 public void Charge() 28 { 29 System.out.println("公交车收费为5毛"); 30 } 31 } 32 class taxi extends Motorvehicles implements MonenyFare , ControlTemperature 33 { 34 35 void brake() 36 { 37 System.out.println("taxi来啦!,嘟嘟"); 38 } 39 public void Charge() 40 { 41 System.out.println("taxi收费为5毛"); 42 } 43 public void ControlAirTemperature() 44 { 45 System.out.println("taxi执行温度控制开关!"); 46 } 47 } 48 class Cinema implements MonenyFare , ControlTemperature 49 { 50 public void Charge() 51 { 52 System.out.println("电影院收费为5毛"); 53 } 54 public void ControlAirTemperature() 55 { 56 System.out.println("电影院执行温度控制开关!"); 57 } 58 } 59 public class example_1 { 60 public static void main(String args[]) 61 { 62 Bus myBus = new Bus(); 63 taxi mytaxi = new taxi(); 64 Cinema mycinema = new Cinema(); 65 myBus.brake(); 66 myBus.Charge(); 67 mytaxi.brake(); 68 mytaxi.Charge(); 69 mytaxi.ControlAirTemperature(); 70 mycinema.Charge(); 71 mycinema.ControlAirTemperature(); 72 } 73 }
/* 公交车来啦!,嘟嘟 公交车收费为5毛 taxi来啦!,嘟嘟 taxi收费为5毛 taxi执行温度控制开关! 电影院收费为5毛 电影院执行温度控制开关! */
接口与多态:
1 /* 2 11.23 22.78 3 a和b的算术平均值为:17.005000000000003 4 a和b的几何平均值为:15.99435525427643 5 6 */ 7 8 9 package st ; 10 import java.util.Scanner; 11 interface c_average 12 { 13 public double average(double a, double b); 14 } 15 // 求算术平均值 16 class A implements c_average 17 { 18 public double average(double a , double b) 19 { 20 return (a+b)/2; 21 } 22 } 23 class B implements c_average 24 { 25 public double average(double a,double b) 26 { 27 return Math.sqrt(a*b); 28 } 29 } 30 public class example_1 31 { 32 public static void main(String args[]) 33 { 34 Scanner reader=new Scanner(System.in); 35 double a,b; 36 a=reader.nextDouble(); 37 b=reader.nextDouble(); 38 A mya = new A(); 39 System.out.println("a和b的算术平均值为:"+mya.average(a, b)); 40 B myb=new B(); 41 System.out.println("a和b的几何平均值为:"+myb.average(a,b)); 42 } 43 } 44