Junior — Middle
Explain the concept of a wrapper class and its purpose in object-oriented programming.
sobes.tech AI
Answer from AI
A wrapper class in object-oriented programming is a class that "wraps" another object or primitive data type, providing additional functionality or an interface. The main purposes of a wrapper class:
- Encapsulating primitive types into objects (for example, in Java, there are wrapper classes for primitives: Integer, Double, etc.).
- Adding extra logic when accessing data or methods.
- Ensuring compatibility with APIs that require objects instead of primitives.
- Managing the lifecycle or state of the wrapped object.
Example: a wrapper class for a string that adds a method to count words.
public class StringWrapper {
private String str;
public StringWrapper(String str) {
this.str = str;
}
public int wordCount() {
if (str == null || str.isEmpty()) return 0;
return str.trim().split("\\s+").length;
}
public String get() {
return str;
}
}
Thus, a wrapper class extends the functionality or adapts the behavior of the original object.