---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity開發</a>、<a href="http://www.itheima.com"target="blank">.Net培訓</a>、期待與您交流! ----------------------
接口
接口:
可以認爲是一個特殊的抽象類,接口沒有構造函數。
當抽象類中的方法都是抽象的,那麼該類可以通過接口的形式來表示。class用於定義類
interface 用於定義接口。接口和抽象類區別:
相同點:都是不斷向上抽取出來的抽象的概念。
區別:
1,抽象類體現繼承關係,一個類只能單繼承;
接口體現實現體系,一個類可以多實現。2,抽象類是繼承,是"is a"關係,就好比是親爹。
接口是實現,是"like a"關係。就好比是乾爹。3,抽象類中可以定義非抽象方法,供子類直接使用。
接口的方法都是抽象方法,接口的中成員都有固定修飾符接口中沒有構造函數。接口中的成員變量都是靜態常量,初始化 時就必須賦值。
接口定義時,格式特點:
1,接口中常見定義:常量,抽象方法。
2,接口中的成員都有固定修飾符。常量:public static final。定義時,必須初始化。一旦賦值就不能修改!
方法:public abstract 訪問級別必須是public,否則會編譯錯誤!注:接口中的成員都是public的。
接口:是不可以創建對象的,因爲有抽象方法。
需要被子類實現,子類對接口中的抽象方法全都覆蓋後,子類纔可以實例化。否則子類是一個抽象類。
接口可以被類多實現,也是對多繼承不支持的轉換形式。java支持多實現。
類與接口的關係:類與接口之間實現implements關係,多實現關係
接口與接口的關係:接口與接口繼承extends關係,接口之間可以支持多繼承extends。接口的特點:
接口是對外暴露的規則。
接口是程序的功能擴展。接口的出現降低耦合性。
接口可以用來多實現。類與接口之間是實現關係,而且類可以繼承一個類的同時實現多個接口。
接口與接口之間可以有繼承關係。
示例代碼:
package com.itheima;
/**
* 接口的示例
* @author wuyong
*
*/
public class InterfaceDemo {
/**
* @param args
*/
public static void main(String[] args)
{
Sun t = new Sun();
System.out.println(t.NUM);
System.out.println(Sun.NUM);
t.show();
t.function();
}
}
/**
* 接口Interface1
* @author wuyong
*
*/
interface Interface1
{
public static final int NUM = 3;
public abstract void show();
}
/**
* 接口Interface2
* @author wuyong
*
*/
interface Interface2
{
public abstract void show();
}
/**
* 父類Father
* @author wuyong
*
*/
class Father
{
public void function(){
System.out.println("Father");
}
}
/**
* 子類Sun,繼承Father類,
* 實現Interface1,Interface2
* @author wuyong
*
*/
class Sun extends Father implements Interface1,Interface2
{
public void show(){
System.out.println("Sun implements Interface1,Interface2");
System.out.println("Interface1's NUM is " + NUM);
}
public void function(){
System.out.println("Sun's SuperClass is Father");
}
}
/**
* 接口A
* @author wuyong
*
*/
interface A
{
void methodA();
// int show();//返回值是int,如果子接口中存在同名方法,但返回值類型不同,則編譯錯誤!
}
/**
* 接口B
* @author wuyong
*
*/
interface B //extends A
{
void methodB();
void show();//返回值是void
}
/**
* 接口C
* @author wuyong
*
*/
interface C extends B,A //類型A和B不兼容; 兩者都定義了show(), 但卻帶有不相關的返回類型
{
void methodC(); //這裏就要繼承兩個,但方法不能重複定義,此時出問題,故不多繼承
}
/**
* 實現類D,實現接口C。此時相當於實現了A,B,C三個接口的功能
* @author wuyong
*
*/
class D implements C
{
public void methodA(){
System.out.println("methodA of interfaceA");
}
public void methodC(){
System.out.println("methodCof interfaceC");
}
public void methodB(){
System.out.println("methodB of interfaceB");
}
@Override
public void show() {
// TODO Auto-generated method stub
System.out.println("Implements Class D");
}
}
---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity開發</a>、<a href="http://www.itheima.com"target="blank">.Net培訓</a>、期待與您交流! ----------------------