Java 8 add extension/default method to class

Java doesn’t have extension methods. Default methods are not extension methods. Let’s look at each feature.

Default methods

Both Java and C# support this feature

Problems solved:

  1. Many objects may implement the same interface and all of them may use the same implementation for a method. A base class could solve this issue but only if the interface implementors don’t already have a base class as neither java nor C# support multiple inheritance.
  2. An API would like to add a method to an interface without breaking the API consumers. Adding a method with a default implementation solves this.

Java’s or C#’s default methods are a feature to add a default implementation to an interface. So objects that extend an interface don’t have to implement the method, they could just use the default method.

interface IA { default public int AddOne(int i) { return i + 1; } }

Any object that implements IA doesn’t have to implement AddOne because there is a default method that would be used.

public class MyClass implements IA { /* No AddOne implementation needed */ } 

C# now has this feature in C# 8 (or .Net 5)

C#’s Extension Method

Problems solved:

  1. Ability to add methods to sealed classes.
  2. Ability to add methods to classes from third-party libraries without forcing inheritance.
  3. Ability to add methods to model classes in environments where methods in model classes are not allowed for convention reasons.
  4. The ability for IntelliSense to present these methods to you.

Example: The type string is a sealed class in C#. You cannot inherit from string as it is sealed. But you can add methods you can call from a string.

var a = "mystring";
a.MyExtensionMethed()

Java lacks this feature and would be greatly improved by adding this feature.

Conclusion

There is nothing even similar about Java’s default methods and C#’s extension method features. They are completely different and solve completely different problems.

Leave a Comment