我想了解Java OOP概念的基礎知識,所以我有一個關於接口的問題,因爲它讓我有點困惑。下面我正在玩兩個班。其中一個實現了SizeComparable接口,另一個則不工作。爲什麼我應該在Java中使用這種接口?
public interface SizeComparable {
int isHigher(SizeComparable obj);
}
public class Interesting implements SizeComparable {
private int height;
public Interesting(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public int isHigher(SizeComparable obj) {
Interesting otherInteresting = (Interesting)obj;
if(this.getHeight() > otherInteresting.getHeight()) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
Interesting i1 = new Interesting(182);
Interesting i2 = new Interesting(69);
int result = i1.isHigher(i2);
System.out.println("Is i1 higher than i2? Result: " + result);
}
}
上面的代碼如何比下面的代碼更好?就我個人而言,我不明白,因爲代碼咆哮那些工作也很棒。我是否錯過了界面構思背後的一些概念?
public class Interesting {
private int height;
public Interesting(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public int isHigher(Interesting obj) {
if(this.getHeight() > obj.getHeight()) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
Interesting i1 = new Interesting(182);
Interesting i2 = new Interesting(69);
int result = i1.isHigher(i2);
System.out.println("Is i1 higher than i2? Result: " + result);
}
}
我試圖理解它(here),但我仍然不確定這一點。對不起,如果這個問題有點愚蠢,我只想完全理解它。
一個接口允許有人從頭開始實現你的接口,或者在原始或主要目的與你的接口完全不同的其他代碼中實現你的接口。 – yogsma 2011-02-28 22:23:17