Java 8 add extension/default method to class

Cheetah picture Cheetah · Jun 7, 2014 · Viewed 33.6k times · Source

I am looking for a java equivalent to the C# extension methods feature. Now I have been reading about Java 8's default methods, but as far as I can see, I can only add these to interfaces...

...is there any language feature that will allow me to write an extension method for a final class that doesn't implement an interface? (I'd rather not have to wrap it...)

Answer

Rhyous picture Rhyous · Sep 6, 2017

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

Java's default methods

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 java doesn't 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 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# lacks this feature and would be greatly improved by adding this feature. (Update: Feature coming in C# 8)

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.