本次講解面向接口interface,其內功能爲計算三角形和圓形的面積。
接口的本身反映了系統設計人員對系統的抽象理解。
接口應有兩類:第一類是對一個體的抽象,它可對應爲一個抽象體(abstract class);
第二類是對一個體某一方面的抽象,即形成一個抽象面(interface);
一個體有可能有多個抽象面。
抽象體與抽象面是有區別的。
接口,英文稱作interface,泛指供別人調用的方法或者函數,它是對行爲的抽象。
在Java中,定義一個接口的形式如下:
public interface InterfaceName {
int a;
public void f();
}
1.接口中可以含有 變量和方法
2.接口中的變量會被隱式地指定爲public static final變量(且只能是public static final變量),方法會被隱式地指定爲public abstract方法且只能是public abstract方法(且只能是public abstract 方法),並且接口中所有的方法不能有具體的實現,也就是說,接口中的方法必須都是抽象方法。
實現接口
讓某一個類實現接口需要使用implements關鍵字
class ClassName implements Interface1,Interface2,[....]{
}
================================================================================================================================
在以下完整測試中
我們會使用到四個類 1.Pillar 2.Geometry 3.Lader 4.Circle 5.Example5_14
.
.
1.Pillar
.
.
.
2. Geometry(接口)
.
.
.
3.Lader
.
.
.
4.Circle
.
.
.
5.Example5_14測試類
.
.
================================================================================================================================
.
我們來看一看代碼實現
.
.
package com.ash.www;
public class Pillar{
Geometry bottom; //將bottom接口變量作爲成員
double height;
Pillar(Geometry bottom, double height){
this.bottom = bottom;
this.height = height;
}
void changeBottom(Geometry bottom){
this.bottom = bottom;
}
public double getVolume() {
return bottom.getArea() * height;
}
}
.package com.ash.www;
public interface Geometry { //接口
public double getArea(); //得到面積
}
.package com.ash.www;
public class Lader implements Geometry {
double a, b, h;
Lader(double a, double b, double h){
this.a = a;
this.b = b;
this.h = h;
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return (1/2.0) * (a+b) * h;
}
}
package com.ash.www;
public class Circle implements Geometry {
double r;
Circle(double r){
this.r = r;
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return (3.14 * r * r);
}
}
package com.ash.www;
public class Example5_14 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Pillar pillar;
Geometry tuxing;
tuxing = new Lader(12, 22, 100);
System.out.println("Lader area: "+ tuxing.getArea());
pillar = new Pillar(tuxing, 58);
System.out.println("Ladered pillar volume: "+ pillar.getVolume());
tuxing = new Circle(10);
System.out.println("When the cicle radius is 10, the circle area: "+ tuxing.getArea());
pillar.changeBottom(tuxing);
System.out.println("Circled pillar volume: "+ pillar.getVolume());
}
}
.