What is binary compatibility in Java?

Java

Java Problem Overview


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 Interfaces for storing constants. I am putting the explanation below.

"Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility."

What does binary compatibility mean here?

Can someone guide me with an example in Java to show that code is binary compatible.

Java Solutions


Solution 1 - Java

In short, binary compatibility means that when you change your class, you do not need to recompile classes that use it. For example, you removed or renamed a public or protected method from this class

public class Logger implements Constants {
   public Logger getLogger(String name) {
         return LogManager.getLogger(name);
   }
}

from your log-1.jar library and released a new version as log-2.jar. When users of your log-1.jar download the new version it will break their apps when they will try to use the missing getLogger(String name) method.

And if you remove Constants interface (Item 17) this will break binary compatibility either, due to the same reason.

But you can remove / rename a private or package private member of this class without breaking the binary compatibility, because external apps cannot (or should not) use it.

Solution 2 - Java

To better understand the concept, it is interesting to see that binary compatibility does NOT imply API compatibility, nor vice versa.

API compatible but NOT binary compatible: static removal

Version 1 of library:

public class Lib {
    public static final int i = 1;
}

Client code:

public class Main {
    public static void main(String[] args) {
        if ((new Lib()).i != 1) throw null;
    }
}

Compile client code with version 1:

javac Main.java

Replace version 1 with version 2: remove static:

public class Lib {
    public final int i = 1;
}

Recompile just version 2, not the client code, and run java Main:

javac Lib.java
java Main

We get:

Exception in thread "main" java.lang.IncompatibleClassChangeError: Expected static field Lib.i
        at Main.main(Main.java:3)

This happens because even though we can write (new Lib()).i in Java for both static and member methods, it compiles to two different VM instructions depending on Lib: getstatic or getfield. This break is mentioned at JLS 7 13.4.10:

> If a field that is not declared private was not declared static and is changed to be declared static, or vice versa, then a linkage error, specifically an IncompatibleClassChangeError, will result if the field is used by a pre-existing binary which expected a field of the other kind.

We would need to recompile Main with javac Main.java for it to work with the new version.

Notes:

Binary compatible but NOT API compatible: null pre-condition strengthening

Version 1:

public class Lib {
    /** o can be null */
    public static void method(Object o) {
        if (o != null) o.hashCode();
    }
}

Version 2:

public class Lib {
    /** o cannot be null */
    public static void method(Object o) {
        o.hashCode();
    }
}

Client:

public class Main {
    public static void main(String[] args) {
        Lib.method(null);
    }
}

This time, even if recompile Main after updating Lib, the second invocation will throw, but not the first.

This is because we changed the contract of method in a way that is not checkable at compile time by Java: before it could take null, after not anymore.

Notes:

  • the Eclipse wiki is a great source for this: https://wiki.eclipse.org/Evolving_Java-based_APIs
  • making APIs that accept null values is a questionable practice
  • it is much easier to make a change that breaks API compatibility but not binary than vice versa, since it is easy to change the internal logic of methods

C binary compatibility example

https://stackoverflow.com/questions/2171177/what-is-an-application-binary-interface-abi/54967743#54967743

Solution 3 - Java

Binary compatibility >Java binary compatibility prescribes conditions under which modication and re-compilation of classes does not necessitate re-compilation of further classes import- ing the modied classes. Binary compatibility is a novel concept for language design.

The Java language specication [7] describes binary com- patible changes as follows:

>A change to a type is binary compatible with (equivalently, does not break compatibility with) pre-existing binaries if pre-existing binaries that previously linked without error will con- tinue to link without error.

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - JavaEvgeniy DorofeevView Answer on Stackoverflow
Solution 2 - JavaCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 3 - JavaSumit SinghView Answer on Stackoverflow
Solution 4 - JavaBIPIN SHARMAView Answer on Stackoverflow