我想了解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