轉(zhuǎn)發(fā)請(qǐng)注明出處:
安卓猴的博客(http://sunjiajia.com)
本節(jié)課程將學(xué)習(xí)以下內(nèi)容:
- 什么是接口
- 接口的基本語(yǔ)法
- 為什么要使用接口
- 工廠方法模式
什么是接口
含義:
Java接口是一系列方法的聲明宽气,一個(gè)接口只有方法的特征沒(méi)有方法的實(shí)現(xiàn)屏积,因此這些方法可以在不同的地方被不同的類實(shí)現(xiàn),而這些實(shí)現(xiàn)可以具有不同的行為(功能)牙言。
接口的基本語(yǔ)法
- 使用interface定義气筋;
- 接口當(dāng)中的方法都是抽象方法(不用寫abstract)薯嗤;
- 接口當(dāng)中的方法都是public權(quán)限(不用寫public)绰寞;
- 實(shí)現(xiàn)接口使用implements關(guān)鍵字;
- 一個(gè)類可以實(shí)現(xiàn)多個(gè)接口泉手;
- 一個(gè)接口可以繼承多個(gè)接口黔寇;
注意:
- 不能生成對(duì)象;
- 用一個(gè)類來(lái)實(shí)現(xiàn)(關(guān)鍵字是implements)接口使用它斩萌;
- 復(fù)寫接口中的抽象方法實(shí)現(xiàn)相應(yīng)的功能缝裤。
例子1:(請(qǐng)動(dòng)手)
1.新建一個(gè)名為USB.java的源文件:
interface USB{
// 它們是public權(quán)限的抽象函數(shù)
void read();
void write();
}
2.新建一個(gè)名為WIFI.java的源文件:
interface WIFI{
// 它們是public權(quán)限的抽象函數(shù)
void open();
void close();
}
3.新建一個(gè)名為USBPhone.java的源文件:
class USBPhone implements USB,WIFI{
void read(){
System.out.println("USBPhone read!");
}
void write(){
System.out.println("USBPhone write!");
}
void open(){
System.out.println("WIFI open!");
}
void open(){
System.out.println("WIFI close!");
}
}
4.新建一個(gè)名為Demo01.java的源文件:
class Demo01{
public static void main(String[] args) {
USBPhone phone = new USBPhone();
// 向上轉(zhuǎn)型
USB usb = phone;
WIFI wifi = phone;
usb.read();
usb.write();
wifi.open();
wifi.close();
}
}
為什么要使用接口
工廠方法模式
- 請(qǐng)反復(fù)練習(xí)下面的例子2,在代碼中深刻理解
為什么要使用接口
和工廠方法模式
颊郎。
- 關(guān)于
工廠方法模式
的定義憋飞,請(qǐng)閱讀百度百科詞條【工廠方法模式】。
例子2:(請(qǐng)動(dòng)手)
1.新建一個(gè)名為Printer.java的源文件:
interface Printer{
void open();
void close();
void print(String s);
}
2.新建一個(gè)名為HPPrinter.java的源文件:
class HPPrinter implements Printer{
void open(){
System.out.println("HP open");
}
void close(){
System.out.println("HP close");
}
void print(String s){
System.out.println("HP print-->" + s);
}
}
3.新建一個(gè)名為CanonPrinter.java的源文件:
class CanonPrinter implements Printer{
private void clean(){
System.out.println("Canon clean");
}
void open(){
System.out.println("Canon open");
}
void close(){
System.out.println("Canon close");
}
void print(String s){
System.out.println("Canon print-->" + s);
}
}
4.新建一個(gè)名為Demo02.java的源文件:
class Demo02{
public static void main(String[] args) {
Printer printer = null;
// 用flag來(lái)模擬用戶選擇打印機(jī)姆吭。
int flag = 0;
if (flag == 0) {
printer = new HPPrinter();
} else if (flag == 1) {
printer = new CanonPrinter();
}
printer.open();
printer.print("abcdefghijklmn");
printer.close();
}
}
5.新建一個(gè)名為PrinterFactory.java的源文件:
class PrinterFactory{
public static Printer getPrinter(int flag){
Printer printer = null;
// 用flag來(lái)模擬用戶選擇打印機(jī)榛做。
if (flag == 0) {
printer = new HPPrinter();
} else if (flag == 1) {
printer = new CanonPrinter();
}
return printer;
}
}
6.新建一個(gè)名為Demo03.java的源文件:
class Demo03{
public static void main(String[] args) {
int flag = 0;
Printer printer = PrinterFactory.getPrinter(flag);
printer.open();
printer.print("abcdefghijklmn");
printer.close();
}
}
- 請(qǐng)注意4、5猾编、6不同寫法的意義瘤睹。