Wrapper Classes Discussion
Why use Wrapper Classes over Primitive Datatypes?
Example for Wrapper Classes
Keep in mind that there is overlap between design patterns and sometimes not everyone agrees on what an implementation looks like. That being said, I would say that a wrapper encloses some class and allows that class to work with some protocol or interface that it originally did not accommodate.
class Ice-T {
sing() {... }
act() { ... }
compose() { ... }
};
But now we have our class in production and we suddenly want it to do the things it already does but in China, where the laws are different. So, we create a wrapper class that encloses our Ice-T class and enforces Chinese laws before permitting calls to sing(), act(), and compose().
class RapperWrapper()
private Ice-T iceT;
void checkAndSing();
void checkAndAct();
void checkAndCompose();
};
But, wait, why don't we just add the logic to our original class and be done with it? Well, we want to maintain separation of concerns. Our wrapper class doesn't know how to sing but it does know how to make sure that Chinese law are complied with before singing is permitted. Also, our original class is already in production and we can't change it: perhaps we're not even allowed to change it because someone else provides it to us.
More on reddit.comI don't understand wrapper classes
Integer b = new Integer(8); b=b+1; System.out.println(b);
here I added 1 to b and I got 9 on the console, I could change the Integer object within the main method
You're not actually "changing" the Integer object here. What you're doing is creating a new Integer, with a value of 9, and then storing it in the b variable, throwing away the old object which had the value 8.
i.e. you're changing the variable to point to a new object, rather than modifying the object in-place.
Modifying / mutating the original object would look something like this - it's not something valid which you can do:
Integer b = new Integer(8); b.increaseBy(1); System.out.println(b);
The difference is subtle, but it also explains why the code in 'main' couldn't "see" the changes made in the 'add' method.
I also used valueOf and parseInt methods, valueOf method returns an Integer object but I assigned an int primitive type to it and it worked. Similarly, I declared an Integer object and assigned it to the result of parseInt method which returns a primitive type and it also worked.
Basically Java will automatically convert between Integer and int for you, based on what's required in any given context.
This is called "automatic boxing / unboxing".
The main reason Integer exists is:
-
It's possible to have a 'null' Integer, but not a null int - if you want to allow a null value, you need to use the object wrapper type
-
Collections like List, Set, Map etc do not support primitive types, only objects - so these object wrapper / boxed versions need to exist to allow you to store primitive values in collections