What is binary compatibility in Java?

后端 未结 5 931
误落风尘
误落风尘 2020-12-13 04:37

I was reading Effective Java by Joshua Bloch.

In Item 17: \"Use interfaces only to define types\", I came across the explanation where it is not advised to use Inte

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 05:08

    If in future, we wish to change the interface that some classes are implementing (e.g., addition of some new methods).

    If we add abstract methods(additional methods), then the classes (implementing the interface) must implements the additional method creating dependency constraint and cost overhead to perform the same.

    To overcome this, we can add default methods in the interface.

    This will remove the dependency to implement the additional methods.

    We do not need to modify the implementing class to incorporate changes. This is called as Binary Compatibility.

    Please refer the example below:

    The interface that we are going to use

        //Interface       
        interface SampleInterface
                {
                    // abstract method
                    public void abstractMethod(int side);
    
                    // default method
                    default void defaultMethod() {
                       System.out.println("Default Method Block");
                    }
    
                    // static method
                    static void staticMethod() {
                        System.out.println("Static Method Block");
                    }
                }
    
    
    //The Class that implements the above interface.
    
        class SampleClass implements SampleInterface
        {
            /* implementation of abstractMethod abstract method, if not implemented 
            will throw compiler error. */
            public void abstractMethod(int side)
            {System.out.println(side*side);}
    
            public static void main(String args[])
            {
                SampleClass sc = new SampleClass();
                sc.abstractMethod(4);
    
                // default method executed
                sc.defaultMethod();
    
                // Static method executed
                SampleInterface.staticMethod();
    
            }
        }
    

    Note: For more detailed information, please refer default methods

提交回复
热议问题