2

In some languages like C# and Objective C, you can create class extensions. That means you can add additional methods to an existing class without having to extend that class. Is this possible in Java?

aryaxt
  • 76,198
  • 92
  • 293
  • 442

5 Answers5

9

As Oli mentions, it is not possible.

It is worth mentioning that an extension method in C# is just a fancy way of calling an Static method, so although it looks like

someobject.MyExtensionMethod();

then the compiler translates that to

SomeStaticClass.MyExtensionMethod(someobject);

You are not really adding a method to the object

Sebastian Piu
  • 7,838
  • 1
  • 32
  • 50
  • Interesting, I didn't know that about C# – aryaxt Dec 11 '11 at 18:55
  • I disagree. Extensions really extend the class. If i, for example, add the method localization() to the String object, i can use that method with any string object. There is no need to use a derivation. – MiguelSlv Jan 20 '17 at 10:55
  • I think you misunderstood what I was implying, and what you say is untrue, you can only call that method if you import the namespace – Sebastian Piu Jan 20 '17 at 12:36
3

No, not with standard Java.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

You could use AspectJ that is using compile-time weaving to add to the bytecode.

dimitrisli
  • 20,895
  • 12
  • 59
  • 63
1

I'm not aware of a language construct, that would allow you to do that, but you could use Decorator pattern to achieve your goal.

Tomáš Plešek
  • 1,482
  • 2
  • 12
  • 21
0

This is possible with the lombok library. There is an annotation that is called @ExtensionMethod.

This gives you that functionality.

See https://projectlombok.org/features/experimental/ExtensionMethod.html