난 그냥 자바를 시작했습니다, 그리고 온라인 예제를 통해가는 : 나는 그 뒤에 개념을 이해하면서, http://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html자바가 필요한 인터페이스를 구현하는 이유는 무엇입니까?
그럼 내가 인터페이스를 구현에 도착,하지만 인터페이스로, 나에게 이상한 것 같다 선언 만하면됩니다.이 인터페이스를 구현하는 클래스에서는 함수를 작성해야합니다. 그렇다면 왜 그것을 전혀 사용하지 않습니까?
예제 코드를 시도한 다음 코드를 변경하여 인터페이스를 제거하면 둘 다 동일하게 작동합니다. 그래서 제 질문은 언제 인터페이스를 구현할 것입니까? 나에게는 불필요 해 보인다. 미리 감사드립니다!
샘플 코드 온라인 : I로 변경
public class RectanglePlus
implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing
// the area of the rectangle
public int getArea() {
return width * height;
}
// a method required to implement
// the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
}
코드, 그것은 여전히 같은
public class RectanglePlus {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing
// the area of the rectangle
public int getArea() {
return width * height;
}
// a method required to implement
// the Relatable interface
public int isLargerThan(RectanglePlus otherRect) {
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
public static void main(String[] args)
{
RectanglePlus newRect = new RectanglePlus(20, 30);
RectanglePlus somerect = new RectanglePlus(50, 100);
System.out.println("Area of newRect is " + newRect.getArea());
System.out.println("Area of somerect is " + somerect.getArea());
if((newRect.isLargerThan(somerect))==1)
{
System.out.println("newRect is bigger");
}
else
{
System.out.println("somerect is bigger");
}
}
}
그러나 수정 된''Relatable'이 예상된다 RectanglePlus' 내가 isLargerThan는 같은 클래스에 객체를 비교할 수있는 튜토리얼은 매우 명확하지 않습니다 생각 ... – MadProgrammer
사용할 수 없습니다. SquarePlus라는 다른 클래스를 작성한 다음 if (newRect.isLargerThan (somesquare) == 1)를 사용하여 두 클래스를 비교해보십시오. 작동하지 않습니다 –