Rih*_*rds 1 java oop interface
我正在尝试理解Java OOP概念的基础知识,所以我对接口提出了一个问题,因为它让我感到困惑.下面我正在玩两节课.一个实现了SizeComparable接口,另一个实现了不同但又有效.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码如何比下面的代码更好?就个人而言,我不明白,因为代码对它的工作也很好.我错过了界面概念背后的一些概念吗?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图理解它(这里),但我仍然不确定这一点.对不起,如果这个问题有点傻,我只想完全理解它.
如果你有Interesting,Boring,Indifferent和Crazy类,所有代表的一些对象的高度相当,然后所有的人都可以实现的SizeComparable接口,因此可以相互媲美.
如果没有接口,您需要在每个类中使用n个方法来将其与自身和所有其他类进行比较.
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |