Sobes.tech
Junior — Middle

Can you explain what extensions are in Java and how they are implemented?

sobes.tech AI

Answer from AI

Java does not have built-in support for extensions like some other languages (e.g., Kotlin). However, the concept of extensions is implemented through static methods in utility classes that take an object as a parameter and add additional functionality to it.

For example, if you need to add a new method to an existing class without modifying its source code, you create a class with static methods:

public class StringExtensions {
    public static boolean isNullOrEmpty(String str) {
        return str == null || str.isEmpty();
    }
}

// Usage:
String s = "";
boolean empty = StringExtensions.isNullOrEmpty(s);

In Android development with Kotlin, extensions are implemented as extension functions and properties, but in pure Java, the described approach must be used.