आप एक विधि ओवरराइड करने के लिए एक उपवर्ग लिए मजबूर नहीं कर सकते हैं। आप केवल इसे अमूर्त बनाकर एक विधि को लागू करने के लिए मजबूर कर सकते हैं।
तो अगर आप myMotherClass सार है कि आप केवल एक और सुपर क्लास कि विधि है कि लागू किया जाना चाहिए करने के लिए myMotherClass और प्रतिनिधियों फैली लागू कर सकते हैं नहीं कर सकते:
public abstract class EnforceImplementation extends myMotherClass {
public final void myMethod(){
implementMyMethod();
}
public abstract void implementMyMethod();
}
संपादित
मैं एक interessting रास्ता मिल गया hemcrest
एपीआई में समस्या को हल करने के लिए उदाहरण है मॉकिटो द्वारा प्रयोग किया जाता है।
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
वर्ग के रूप में अंतिम
public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
// See Matcher interface for an explanation of this method.
}
अंत में मुझे लगता है कि यह एक डिजाइन समस्या है _dont_implement_Matcher___instead_extend_BaseMatcher_
विधि को लागू करता है, क्योंकि BaseMatcher
obviouosly तर्क है कि हर Matcher
को लागू करना चाहिए लागू करता है। इस प्रकार Matcher
एक अमूर्त वर्ग बनाने और टेम्पलेट विधि का उपयोग करना बेहतर होता।
लेकिन मुझे लगता है कि उन्होंने ऐसा किया क्योंकि यह बाइटकोड संगतता और नई सुविधाओं के बीच सबसे अच्छा समझौता था।
स्रोत
2013-08-20 09:28:00
संक्षेप में: आप इसे अमूर्त बनाने के बिना नहीं कर सकते –
@stonedsquirrel एक इंटरफेस के बारे में क्या? –
एनोटेशन का उपयोग करना या अपवाद फेंकना संभव नहीं है यदि वर्ग विधि को लागू नहीं करता है? – Maniz