JAVA 接口的基本語法

定義ide

  1. 使用interface定義
  2. 接口當中的方法都是抽象方法
  3. 接口當中的方法都是public權限

實現spa

  1. 實現接口使用implements關鍵字
  2. 一個類能夠實現多個接口
  3. 一個接口能夠繼承多個接口

一個類能夠實現多個接口code

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();
    }

}

運行結果blog

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
相關文章
相關標籤/搜索