javaclass-extensions

Creating an extension to a class?


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?


Solution

  • 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