Junior — Middle
What object-oriented programming principle do generics implement?
sobes.tech AI
Answer from AI
Generic types in Java implement the principle of parameterization of types, which allows creating classes, interfaces, and methods that work with different data types while ensuring type safety during compilation. This is related to the principle of polymorphism in object-oriented programming, as it allows using the same code for different types, avoiding duplication and type casting errors.
Example of using Generics:
public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
Box<String> stringBox = new Box<>();
stringBox.setContent("Example");
String value = stringBox.getContent();
Here, T is a type parameter that is replaced with a specific type when creating an object.