2013-08-20 3 views
11

하위 클래스에서 내 모더 클래스의 구현 된 메서드를 구현하도록하고 싶습니다. 이걸 보니 Java - Force implementation of an implemented method하지만 내 모범 클래스는 추상 클래스로 변환 할 수 없습니다.추상을 사용하지 않고 하위 클래스에서 메서드를 강제로 구현하는 방법은 무엇입니까?

public class myMotherClass { 

    myMethod { 

     ...some code .. 

    } 

} 

public class myClass extends myMotherClass { 

    myMethod { 

     ... other code ... 
    } 

} 

따라서이 예제에서는 myClass가 myMethod를 구현하도록하고 싶습니다. 당신의 구체적인 클래스는 나무의 잎이되도록 내 영어 죄송합니다

...

+1

요약하면 추상화 할 수 없습니다. –

+0

@stonedsquirrel 인터페이스는 어떻습니까? –

+0

주석을 사용하거나 클래스가 메서드를 구현하지 않은 경우 예외를 throw하여이 작업을 수행 할 수 없습니까? – Maniz

답변

16

구현해야합니다. 추상화 만하면 메소드를 구현할 수 있습니다.

당신은 당신 만 구현되어야하는 방법에 myMotherClass 위임을 확장 또 다른 슈퍼 클래스 도입 할 수 myMotherClass 추상적 할 수 없습니다 그래서 경우 :

public abstract class EnforceImplementation extends myMotherClass { 

     public final void myMethod(){ 
      implementMyMethod(); 
     } 

     public abstract void implementMyMethod(); 
} 

편집 내가 다른 interessting 방법을 발견

을 예를 들어 hemcrest API의 문제를 해결하는 방법 mockito에 의해 사용됩니다.

public interface Matcher<T> extends SelfDescribing { 

    /** 
    * Evaluates the matcher for argument <var>item</var>. 
    * <p/> 
    * This method matches against Object, instead of the generic type T. This is 
    * because the caller of the Matcher does not know at runtime what the type is 
    * (because of type erasure with Java generics). It is down to the implementations 
    * to check the correct type. 
    * 
    * @param item the object against which the matcher is evaluated. 
    * @return <code>true</code> if <var>item</var> matches, otherwise <code>false</code>. 
    * 
    * @see BaseMatcher 
    */ 
    boolean matches(Object item); 

    /** 
    * This method simply acts a friendly reminder not to implement Matcher directly and 
    * instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore 
    * compile errors . 
    * 
    * @see Matcher for reasons why. 
    * @see BaseMatcher 
    */ 
    void _dont_implement_Matcher___instead_extend_BaseMatcher_(); 
} 

인터페이스는 _dont_implement_Matcher___instead_extend_BaseMatcher_ 메서드를 지정합니다. 물론 다른 사람들이 Matcher 인터페이스를 구현하는 것을 막지는 못하지만 올바른 방향으로 개발자를 안내합니다.

그리고 BaseMatcher이 obviouosly 모든 Matcher가 구현해야 로직을 구현하기 때문에 BaseMatcher 클래스는

public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() { 
    // See Matcher interface for an explanation of this method. 
} 

마지막으로 나는이 디자인 문제라고 생각합니다 최종

_dont_implement_Matcher___instead_extend_BaseMatcher_ 방법을 구현한다. 따라서 Matcher을 추상 클래스로 만들고 템플릿 메서드를 사용하는 것이 좋습니다.

그러나 바이트 코드 호환성과 새로운 기능 간의 최상의 절충안 이었기 때문에이 코드를 사용했다고 생각합니다.당신이 수용 테스트의 일부 형태를 따른다으로

public class MyMotherClass { 

    public void myMethod() { 
     throw new RuntimeException("Method not overwritten"); 
    }  

} 

는 대부분의 경우이 충분해야한다 : (내가 코멘트에서 그것의 언급을보고 있지만) 대부분의 사람들이 내려다 보이는

4

당신은 당신의 계층 구조를 재 작업 할 수있다. 대신

myClass extends myMotherClass 

myClass extends myMotherAbstractClass 
myMotherClass extends myMotherAbstractClass 

추상 클래스 모두 인스턴스화 클래스에 의해 상속이 방법을 고려하십시오. 이 경우에는 myMotherClass이 매우 얇을 것이고, 구현은 myMethod 일 것입니다.

-1

실제로 구현 방법을 구현하려면 interface을 사용해야합니다. 어떤 하나 MyClass implements MyInterface로이 인터페이스에서 구현하려는 경우

public interface MyInterface{ 

    void myMethod(); 
} 

지금, 당신은 당신이 메소드를 오버라이드 (override)하는 서브 클래스를 강요 할 수 myMethod();

public MyClass implements MyInterface{ 

    public void myMethod{ 
    // do something 
    } 

} 
+2

나는 이것이 문제를 해결할 것이라고 생각하지 않는다. – Lokesh

0

것은 다음과 같은 구현 (상속 클래스를 손으로 만 테스트하는 경우에도 마찬가지 임). 이론적으로, 당신은 여전히 ​​방법이 생산까지 지나치게 압도되지 않았다는 것을 아무도 깨닫지 못할 가능성을 소개하고 있습니다.