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 } 
  • 相关阅读:
    C++ 项目和资源导引
    C++ 类再探
    C++ 语句函数再探
    leetcode-174. Dungeon Game 地下城游戏
    34. Find First and Last Position of Element in Sorted Array + 二分
    leetcode-27. Remove Element删除元素
    git 使用入门
    MySQL数据库的启动与停止
    C++类型转换
    C++ 获取对象类型
  • 原文地址:https://www.cnblogs.com/zhangfan94/p/4263306.html
Copyright © 2011-2022 走看看