Optional Methods in Java Interface

后端 未结 12 1809
说谎
说谎 2020-11-30 20:53

From my understanding if you implement an interface in java, the methods specified in that interface have to be used by the sub classes implementing the said interface.

相关标签:
12条回答
  • 2020-11-30 21:23

    I was looking for a way to implement the call back interface, so implementing optional methods was necessary since I didn't want to implement every method for each call back.

    So, instead of using an interface, I used a class with empty implementation such as:

    public class MyCallBack{
        public void didResponseCameBack(String response){}
    }
    

    And you can set member variable CallBack like this,

    c.setCallBack(new MyCallBack() {
        public void didResponseCameBack(String response) {
            //your implementation here
        }
    });
    

    then call it like this.

    if(mMyCallBack != null) {
        mMyCallBack.didResponseCameBack(response);
    }
    

    This way, you wouldn't need to worry about implementing every methods per call back, but only override the ones you need.

    0 讨论(0)
  • 2020-11-30 21:25

    In order to compile an implementing (non abstract) class for an interface - all methods must be implemented.

    However, if we think of a method that its implementation is a simple exception throw as a 'non implemented' (like some methods in the Collection interface), then the Collection interface is the exception in this case, not the regular case. Usually, implementing class should (and will) implement all methods.

    The "optional" in collection means that the implementing class doesn't have to 'implement' (according to the terminology above) it, and it will just throw NotSupportedException).

    A good example- add() method for immutable collections - the concrete will just implement a method that does nothing but throwing NotSupportedException

    In the case of Collection it is done to prevent messy inheritence trees, that will make programmers miserable - but for most cases, this paradigm is not advised, and should be avoided if possible.


    Update:

    As of java 8, a default method was introduced.

    That means, an interface can define a method - including its implementation.
    This was added in order to allow adding functionality to interfaces, while still supporting backward compatability for pieces of code that does not need the new functionality.

    Note that the method is still implemented by all classes that declare it, but using the interface's definition.

    0 讨论(0)
  • 2020-11-30 21:25

    In fact, I am inspired by SurfaceView.Callback2 . I think this is the official way

    public class Foo {
        public interface Callback {
            public void requiredMethod1();
            public void requiredMethod2();
        }
    
        public interface CallbackExtended extends Callback {
            public void optionalMethod1();
            public void optionalMethod2();
        }
    
        private Callback mCallback;
    }
    

    If your class doesnt need to implement optional methods, just "implements Callback". If your class need to implement optional methods, just "implements CallbackExtended".

    Sorry for shit English.

    0 讨论(0)
  • 2020-11-30 21:25

    Although it does not answer the OP's question, it is worth noting that as of Java 8 adding default methods to interfaces is in fact doable. The default keyword placed in an interface's method signature will result in a class having the option to override the method, but not require it to.

    0 讨论(0)
  • 2020-11-30 21:29

    An interface in Java just declares the contract for implementing classes. All methods in that interface must be implemented, but the implementing classes are free to leave them unimplemented, viz., blank. As a contrived example,

    interface Foo {
      void doSomething();
      void doSomethingElse();
    }
    
    class MyClass implements Foo {
      public void doSomething() {
         /* All of my code goes here */
      }
    
      public void doSomethingElse() {
        // I leave this unimplemented
      }
    }
    

    Now I have left doSomethingElse() unimplemented, leaving it free for my subclasses to implement. That is optional.

    class SubClass extends MyClass {
        @Override
        public void doSomethingElse() {
          // Here's my implementation. 
        }
    }
    

    However, if you're talking about Collection interfaces, as others have said, they are an exception. If certain methods are left unimplemented and you call those, they may throw UnsupportedOperationException exceptions.

    0 讨论(0)
  • 2020-11-30 21:31

    In Java 8 and later, the answer to this question is still valid but is now more nuanced.

    First, these statements from the accepted answer remain correct:

    • interfaces are meant to specify their implicit behaviors in a contract (a statement of rules for behavior that implementing classes must obey in order to be considered valid)
    • there is a distinction between the contract (rules) and the implementation (programmatic coding of the rules)
    • methods specified in the interface MUST ALWAYS be implemented (at some point)

    So, what is the nuance that is new in Java 8? When speaking of "Optional Methods" any of the following are now apt:

    1. A method whose implementation is contractually optional

    The "third statement" says that abstract interface methods must always be implemented and this remains true in Java 8+. However, as in the Java Collections Framework, it is possible to describe some abstract interface methods as "optional" in the contract.

    In this case, the author who is implementing the interface can choose not to implement the method. The compiler will insist upon an implementation, however, and so the author uses this code for any optional methods that are not needed in the particular implementation class:

    public SomeReturnType optionalInterfaceMethodA(...) {
        throw new UnsupportedOperationException();
    }
    

    In Java 7 and earlier, this was really the only kind of "optional method" that there was, i.e. a method that, if not implemented, threw an UnsupportedOperationException. This behavior is necessarily specified by the interface contract (eg. the optional interface methods of the Java Collections Framework).

    2. A default method whose re-implementation is optional

    Java 8 introduced the concept of default methods. These are methods whose implementation can be and is provided by the interface definition itself. It is generally only possible to provide default methods when the method body can be written using other interface methods (i.e., the "primitives"), and when this can mean "this object whose class has implemented this interface."

    A default method must fulfill the contract of the interface (just like any other interface method implementation must). Therefore, specifying an implementation of the interface method in an implementing class is at the author's discretion (as long as the behavior is suitable to his or her purpose).

    In this new environment, the Java Collections Framework could be rewritten as:

    public interface List<E> {
        :
        :
        default public boolean add(E element) {
            throw new UnsupportedOperationException();
        }
        :
        :
    }
    

    In this way, the "optional" method add() has the default behavior of throwing an UnsupportedOperationException if the implementing class provides no new behavior of its own, which is exactly what you would want to have happen and which is compliant with the contract for List. If an author is writing a class that does not allow new elements to be added to a List implementation, the implementation of add() is optional because the default behavior is exactly what is needed.

    In this case, the "third statement" above still holds true, because the method has been implemented in the interface itself.

    3. A method that returns an Optional result

    The final new kind of optional method is simply a method which returns an Optional. The Optional class provides a decidedly more object-oriented way of dealing with null results.

    In a fluent style of programming, such as the kind commonly seen when coding with the new Java Streams API, a null result at any point causes the program to crash with a NullPointerException. The Optional class provides a mechanism for returning null results to client code in a way that enables the fluent style without causing client code to crash.

    0 讨论(0)
提交回复
热议问题