JAVA 接口的基本语法

定义

  1. 使用interface定义
  2. 接口当中的方法都是抽象方法
  3. 接口当中的方法都是public权限

实现

  1. 实现接口使用implements关键字
  2. 一个类可以实现多个接口
  3. 一个接口可以继承多个接口

一个类可以实现多个接口

public interface USB {

    void read();

    void write();
}
public interface WiFi {

    void open();

    void close();
}
public class Phone implements USB, WiFi {

    public Phone() {
        // TODO Auto-generated constructor stub
        System.out.println("Phone 无参构造");
    }

    @Override
    public void open() {
        // TODO Auto-generated method stub
        System.out.println("open");
    }

    @Override
    public void close() {
        // TODO Auto-generated method stub
        System.out.println("close");
    }

    @Override
    public void read() {
        // TODO Auto-generated method stub
        System.out.println("read");
    }

    @Override
    public void write() {
        // TODO Auto-generated method stub
        System.out.println("write");
    }

}
public class Test {

    public Test() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        USB usb = new Phone();
        usb.write();
        usb.read();

        WiFi wiFi = new Phone();
        wiFi.open();
        wiFi.close();
    }

}

运行结果

Phone 无参构造
write
read
Phone 无参构造
open
close

一个接口可以继承多个接口

public interface PhoneDevice extends USB, WiFi {

    void connect();
    
}
public class Phone implements PhoneDevice {

    public Phone() {
        // TODO Auto-generated constructor stub
        System.out.println("Phone 无参构造");
    }

    @Override
    public void read() {
        // TODO Auto-generated method stub
        System.out.println("read");
    }

    @Override
    public void write() {
        // TODO Auto-generated method stub
        System.out.println("write");
    }

    @Override
    public void open() {
        // TODO Auto-generated method stub
        System.out.println("open");
    }

    @Override
    public void close() {
        // TODO Auto-generated method stub
        System.out.println("close");
    }

    @Override
    public void connect() {
        // TODO Auto-generated method stub
        System.out.println("connect");
    }

}

运行结果

Phone 无参构造
write
read
Phone 无参构造
open
close
Phone 无参构造
connect
posted @ 2020-09-02 15:37  thomas_blog  阅读(33)  评论(0编辑  收藏