Java筆記:包與接口
阿新 • • 發佈:2018-02-12
ack str int ora stat 更多 get gre pan
一、包
使用package關鍵字聲明包。包的作用相當於命名空間。若沒有顯式地聲明類所屬的包,那麽類將會被放到默認的包中,默認的包沒有名稱。包支持層次化地創建,即支持嵌套。
使用import關鍵字導入包。支持導入包中的類或包,若不導入聲明變量則需要寫上完整的路徑。
import java.lang.*;//導入包 import java.util.ArrayList;//導入類 class Solution { ArrayList arrayList;//已導入 java.util.LinkedList linkedList;//未導入 }
二、接口
聲明接口。接口的普通方法不能存在具體實現。
interface Color { void setColor(int color); int getColor(); } interface Line { void setLength(int length); int getLength(); }
實現接口。類可以同時實現多個接口。
class ColorfulLine implements Color, Line { int color; int length; ColorfulLine(int color, int length) { this.color = color;this.length = length; } @Override public void setColor(int color) { this.color = color; } @Override public int getColor() { return color; } @Override public void setLength(int length) { this.length = length; } @Override publicint getLength() { return length; } }
嵌套接口。接口為類或其他接口的成員時,有更多的訪問限制選擇。
class A { public interface i { boolean isNegative(int x); } } class B implements A.i { @Override public boolean isNegative(int x) { return x < 0; } }
接口變量。可使用接口將共享的常量導入多個類種。
interface RBG { int RED = 0; int BLUE = 1; int GREEN = 2; }
擴展接口。接口可以繼承其他接口。
interface Color extends RBG { int ORANGE = 3; int YELLOW = 4; int CYAN = 5; int PURPLE = 6; }
默認實現。接口可聲明默認方法並可重寫。
interface i { default void show() { System.out.println("Hi"); } } class A implements i { @Override public void show() { System.out.println("Hello"); } }
變量成員與靜態方法可直接被調用。
interface i { int val = 0; static void show() { System.out.println(val); } } class Solution { public static void main(String[] args) { i.show(); System.out.println(i.val); } }
Java筆記:包與接口