zoukankan      html  css  js  c++  java
  • JAVA学习--接口的应用

     1 public class TestUSB {
     2     public static void main(String[] args) {
     3         Computer com = new Computer();
     4         com.doWork(new Printer());
     5         
     6         Flash f = new Flash();
     7         com.doWork(f);
     8         
     9         //实现接口的匿名类的对象
    10         USB phone = new USB(){
    11             @Override
    12             public void start() {
    13                 System.out.println("手机开始工作");
    14             }
    15             @Override
    16             public void stop() {
    17                 System.out.println("手机停止连接");
    18             }
    19             
    20         };
    21         com.doWork(phone);
    22         
    23         
    24         //实现接口的匿名类的对象
    25         com.doWork(new USB(){
    26             @Override
    27             public void start() {
    28                 System.out.println("手机开始工作");
    29             }
    30             @Override
    31             public void stop() {
    32                 System.out.println("手机停止连接");
    33             }
    34         });
    35     }
    36 }
    37 
    38 class Computer{
    39     public void doWork(USB usb){
    40         usb.start();
    41         System.out.println("。。。此设备开始操作。。。");
    42         usb.stop();
    43     }
    44 }
    45 
    46 interface USB{
    47     //USB的尺寸的大小,可以设置为常量
    48     
    49     //功能设置为抽象方法
    50     void start();
    51     void stop();
    52 }
    53 //打印机
    54 class Printer implements USB{
    55     public void start(){
    56         System.out.println("打印机开始工作");
    57     }
    58     public void stop(){
    59         System.out.println("打印机停止工作");
    60     }
    61 }
    62 //U盘
    63 class Flash implements USB{
    64     public void start(){
    65         System.out.println("U盘开始工作");
    66     }
    67     public void stop(){
    68         System.out.println("U盘停止工作");
    69     }
    70 } 
  • 相关阅读:
    java实现前n项和,要求不使用循环、乘除法、判断标识
    java 线程池 带返回值
    java 多线程 数据通信
    jedis使用分布式锁
    记一次自定义管理工厂使用spring自动装载bean
    面试题玩数组
    记一次随便排序算法
    九九乘法表打印记一次al面试
    多线程操作共享变量顺序输出abc 记一次al面试题
    博客迁移
  • 原文地址:https://www.cnblogs.com/zhangfan94/p/4263306.html
Copyright © 2011-2022 走看看