A wrapper is an OOP technique where an object encapsulates (wraps) another object, resource (dynamically allocated memory, OS file/widow handle, socket, thread mutex, etc) or a set of subroutines, hiding/protecting it and providing another (possibly easier to use) interface. When using this tag on implementation heavy questions - tag the code language the implementation is written in.
A Wrapper is an Object which contains another data type, Object, resources, or subroutines for the purpose of encapsulation. The corresponding class of that Wrapper is the wrapper class.
Often when we refer to a wrapper class we often refer to a primitive wrapper class, where instances of that class encapsulate a primitive type.
Many object-oriented languages, such as Java, differentiate between primitive types (such as char
) and Objects (such as String
), for example that primitive values are passed on by value and are the simplest data types, whereas Objects are passed on by reference and that it includes their own fields and methods. The names of primitive data types are also usually keywords, as opposed to Objects.
In some cases, you may need an instance of a wrapper class for these primitives to perform boxing, treat these primitives as Objects due to OOP reasons, converting a primitive to another Object type, or when using an otherwise primitive value when polymorphism is required. The name of the corresponding primitive wrapper class for a given primitive data type are written in full and follow naming conventions for classes (such as beginning with an uppercase in Java).
Java wrapper classes:
Java offers these wrapper classes which you can use without importing anything. Note that their names begin with an uppercase, and are written in full.
Boolean
for booleansCharacter
for charInteger
for intLong
for 64-bit intDouble
for boudleByte
for byteShort
for shortFloat
for float
Tags related to wrapper operations:
- boxing: Converting a primitive to an Object
- unboxing: Converting an Object back to a primitive
- autoboxing: Java term where the Java compiler automatically converts a primitive type to its corresponding Object. Java documentation about autoboxing and unboxing: