19. Wrapper Class - CS2030S Programming Methodology II
We have seen the following general code that takes in an array of Object objects, and searches if another object obj is in the given array. Through polymorphism and overriding of the equals method, we can make sure that it is general enough to work on any reference type. But what about primitive types? Do we need to write a separate function for each primitive type, like this? Java provides wrapper classes for each of its primitive types. A wrapper class is a class that encapsulates a type, rather than fields and methods. The wrapper class for int is called Integer, for double is called Double, etc. A wrapper class can be used just like every other class in Java and behave just like every other class in Java. In particular, they are reference types and their instances can be created with new; instances are stored on the heap, etc. For instance, The code snippet above shows how we can convert a primitive int value to a wrapper instance i of type Integer, and how the intValue method can
Unit 19: Wrapper Class After this unit, students should: be aware that Java provides wrapper classes around the primitive types be aware that Java will transparently and automatically box and unbox between primitive types and their corresponding wrapper classes Writing General Code for Primitive Types We have seen the following general code that takes in an array of Object objects, and searches if another object obj is in the given array . 1 2 3 4 5 6 7 8 9 // version 0.1 (with polymorphism) boolean contains ( Object [] array , Object obj ) { for ( Object curr : array ) { if ( curr . equals (
Explore this link on the map →saved by
related reading
- 4. Encapsulation - CS2030S Programming Methodology IInus-cs2030s.github.io
- 14. Polymorphism - CS2030S Programming Methodology IInus-cs2030s.github.io
- 21. Variance - CS2030S Programming Methodology IInus-cs2030s.github.io
- 17. Abstract Class - CS2030S Programming Methodology IInus-cs2030s.github.io
- 2. Variable and Type - CS2030S Programming Methodology IInus-cs2030s.github.io
- 20. Casting - CS2030S Programming Methodology IInus-cs2030s.github.io
- Lab 1: Simulation I - CS2030S Programming Methodology IInus-cs2030s.github.io
- abseil / Performance Hintsabseil.io
- artima - Josh Bloch on Designartima.com
- how I think when I think about programming - alice mazalicemaz.com
- Immutable object - Wikipediaen.wikipedia.org
- 9. Classes — Python 3.14.6 documentationdocs.python.org