介面的主要目的是制定軟體組件的共同規則,由於繼承 (inheritance) 只能由單一直線進行,也就是說子類別 (subclass) 只能繼承自某一特定的父類別 (superclass) 。介面提供了另一種彈性,使子類別在繼承父類別的特性之外,也能具有其他型態的特性。
舉例如下
interface Shape {
public double Shape_PI = 3.14;
public double area();
public double perimeter();
}
class Circle implements Shape {
private double radius;
public Circle(double r) {
setRadius(r);
}
public Circle() {
this(10.0);
}
public double getRadius() {
return radius;
}
public void setRadius(double r) {
if (r > 0.0) {
radius = r;
}
else {
radius = 1;
}
}
public double area() {
return radius * radius * Shape_PI;
}
public double perimeter() {
return 2 * radius * Shape_PI;
}
}
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double l, double w) {
setLength(l);
setWidth(w);
}
public Rectangle(double a) {
this(a, 10.0);
}
public Rectangle() {
this(10.0, 10.0);
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public void setLength(double l) {
if (l > 0) {
length = l;
}
else {
length = 1.0;
}
}
public void setWidth(double w) {
if (w > 0) {
width = w;
}
else {
width = 1.0;
}
}
public double area() {
return length * width;
}
public double perimeter() {
return 2 * (length + width);
}
}
class InterfaceDemo {
public static void main(String[] args) {
Circle a = new Circle(15.6);
System.out.println("圓的半徑是" + a.getRadius());
System.out.println("圓的周長是" + a.perimeter());
System.out.println("圓的面積是" + a.area());
Rectangle b = new Rectangle(20.0, 16.0);
System.out.println("長方形的長是" + b.getLength());
System.out.println("長方形的寬是" + b.getWidth());
System.out.println("長方形的周長是" + b.perimeter());
System.out.println("長方形的面積是" + b.area());
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:InterfaceDemo.java
功能:示範物件導向的基本觀念
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

第 1 行到第 6 行
interface Shape {
public double Shape_PI = 3.14;
public double area();
public double perimeter();
}這是介面 Shape 的定義,注意,介面定義中需要宣告有哪些常數及方法,方法由類別來實作,也就是在類別中才詳細定義方法的內容。
第 8 行
class Circle implements Shape {及第 41 行
class Rectangle implements Shape {類別 Circle 及 Rectangle 都有實作 Shape ,因此類別定義中都需將 area() 與 perimeter() 兩個方法的實際內容定義出來。
| 中英文術語對照 | |
|---|---|
| 介面 | interface |
| 參考型態 | reference type |
| 常數 | constant |
| 方法 | method |
| 類別 | class |
| 實作 | implement |
| 繼承 | inheritance |
| 子類別 | subclass |
| 父類別 | superclass |
參考資料
http://download.oracle.com/javase/tutorial/java/IandI/createinterface.html
http://download.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
http://download.oracle.com/javase/tutorial/java/IandI/usinginterface.html
http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html
http://download.oracle.com/javase/tutorial/java/IandI/createinterface.html
http://download.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
http://download.oracle.com/javase/tutorial/java/IandI/usinginterface.html
http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html
沒有留言:
張貼留言