Learn the concepts of Wrapper Classes and Interfaces in Java, their purpose, implementation, and real-world use cases in object-oriented programming.
A Wrapper Class in Java provides an object representation for primitive data types. It allows primitives (like int, float, char) to be treated as objects. This is especially helpful when working with collections such as ArrayList or frameworks that only accept objects.
1️⃣ Convert primitive data types into objects (known as Autoboxing).
2️⃣ Convert objects back into primitive types (Unboxing).
3️⃣ Provide various utility methods for parsing and type conversion.
✔ Supports full object-oriented programming principles.
✔ Enables primitives to work with Java Collection Framework.
✔ Simplifies type conversion and parsing operations.
❌ Increased memory usage due to object creation.
❌ Performance overhead compared to primitive types.
public class WrapperExample {
public static void main(String[] args) {
int num = 10; // primitive type
Integer obj = num; // autoboxing
int val = obj; // unboxing
System.out.println("Value: " + val);
}
}
int value 10 is automatically converted into an Integer object (autoboxing),
and then back to primitive (unboxing). This feature was introduced in Java 5 to make code cleaner and object-friendly.
int → Integer
char → Character
boolean → Boolean
float → Float
double → Double
long → Long
An Interface in Java acts as a blueprint of a class. It contains abstract methods (without implementation) and constants. Interfaces help achieve abstraction and multiple inheritance in Java, allowing flexibility and modular code.
1️⃣ Define a common contract for all implementing classes.
2️⃣ Achieve complete abstraction by hiding implementation details.
3️⃣ Enable multiple inheritance of behavior across unrelated classes.
✔ Promotes loose coupling between components.
✔ Supports abstraction and polymorphism.
✔ Encourages code reusability and scalability.
❌ Cannot include method implementations (till Java 7).
❌ May increase complexity when multiple interfaces are used.
interface Animal {
void sound(); // abstract method
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
Animal interface defines a contract method sound().
The Dog class implements this interface and provides the body for the method.
This ensures every animal type can define its own sound behavior.
✔ Use interfaces to define common behavior among unrelated classes.
✔ Use default methods (Java 8+) for reusable implementations.
✔ Always prefer interface references to achieve loose coupling and flexibility.