2013-10-14 1 views
0

난 그냥 자바를 시작했습니다, 그리고 온라인 예제를 통해가는 : 나는 그 뒤에 개념을 이해하면서, 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"); 
    } 

} 

} 
+2

그러나 수정 된''Relatable'이 예상된다 RectanglePlus' 내가 isLargerThan는 같은 클래스에 객체를 비교할 수있는 튜토리얼은 매우 명확하지 않습니다 생각 ... – MadProgrammer

+0

사용할 수 없습니다. SquarePlus라는 다른 클래스를 작성한 다음 if (newRect.isLargerThan (somesquare) == 1)를 사용하여 두 클래스를 비교해보십시오. 작동하지 않습니다 –

답변

2

두 가지 이유 :

  1. 당신이 인터페이스의 하나 이상의 구현이됩니다. Shape이 있고 부속 유형이 Rectangle, Oval 인 경우 등 일반적으로 모양을 사용하여 작업을 수행 할 수있는 코드를 작성하려면 모든 부속 유형이 구현하는 인터페이스가 필요합니다. 인터페이스는 사용자가 알고있는 메소드 세트입니다 Shape 있습니다.

  2. API를 작성 중이라면 다른 사람이 사용할 라이브러리를 작성하고있는 것입니다. 당신은 다른 사람들에게 인터페이스를 제공합니다 - 이것은 그들이 전화하는 것이 괜찮은 물건입니다. 인터페이스를 구현하고 구현 클래스에 메소드가 추가 될 수 있습니다. 나중에이 메소드를 변경할 수는 있지만 사용자가 라이브러리의 새 버전을 선택하여 이전 코드와 함께 사용할 수 있어야합니다. . 인터페이스를 구현과 분리함으로써 공용으로 사용할 수있는 것을 제공하지만 기존 사용자를 해치지 않으면 서 변경할 수있는 것을 그대로 유지합니다.

+0

감사합니다. 그러나 SquarePlus라는 새 클래스를 정의하고 newRect.isLargerThan (somesquare)을 사용하여 두 클래스를 비교하려고하면 SquarePlus를 RectanglePlus로 캐스팅 할 수 없다고합니다. 나는 그것을 사용하는 방법에 대해 더 많이 읽을 필요가 있다고 생각한다. –

+0

기회의 예가 될 수있는 기회?Square와 Rectangle 클래스를 비교하려면 isLargerThan 인터페이스를 사용하는 방법. 감사. –

+0

물론, 인터페이스에''newRectIsLargerThan()''을 포함하면됩니다. –

0

이 유형/인터페이스 재사용을 촉진하는 것입니다 작동, 인터페이스를 가지고. 상위 유형 객체가 예상되는 하위 유형의 객체를 전달할 수 있습니다. http://www.oodesign.com/liskov-s-substitution-principle.html을 참조하십시오.

기본적으로 추상적 인 방식으로 처리 할 수 ​​있습니다. 프로그램은 특정 동작을 구현하거나 인터페이스를 구현하거나 클래스에서 확장하는 경우 다른 클래스의 객체를 처리 할 수 ​​있습니다.

+0

해당 링크 예제는 확장 용입니다 –

0

Relatable을 구현하면 객체 쌍에서 가장 큰 객체를 찾을 수 있습니다. Relatable를 구현 한 클래스에서 인스턴스화 된 객체 그렇지 않으면 동일한 클래스에서 인스턴스화 된 객체 쌍에서 가장 큰 객체 만 찾을 수 있습니다.