Wrapper Classes In Java

Wrapper Classes:

Wrapper classes were introduced with the discussion of the primitive data types. Primitive values in Java are not  objects. In order to manipulate these values as objects, the java.lang package provides a wrapper class for each of the primitive data  types. All wrapper classes are final. The objects of all wrapper classes that can be instantiated are immutable, that is, their state cannot be  changed.

Although the Void class is considered a wrapper class, it does not wrap any primitive value and is not instantiable. It just denotes the Class object representing the keyword void.

In addition to the methods defined for constructing and manipulating objects of primitive values, the wrapper classes also define useful  constants, fields, and conversion methods.

When working with numbers, most of the time you use the primitive types in your code. For example:

int i = 500;
float gpa = 3.65f;
byte mask = 0xff;

There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapper classes for each of the primitive data types. These classes “wrap” the primitive in an object. Often, the wrapping is done by the compiler—if you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you.

All of the numeric wrapper classes are subclasses of the abstract class Number:


Primitive class 


Wrapper class coreesonding to their respective primitives 



System.out.println(a[i] + “is a digit “);
System.out.println(a[i] + “is a letter “);

Byte class methods:

byteValue() – returns the Byte value as byte value
Ex : byte bvalue = Byte.byteValue();
parseByte() – returns byte value from a byte string
Ex: byte bvaue = Byte.parseByte(“93”);

Integer class methods:

intValue() – returns the Integer value as int value
Ex: int bvalue = Integer.intValue();
parseInt() – returns int value from a int string
Ex: int bvaue = Integer.parseInt(“73”);

Usage of Wrapper Classes:

They should be used in situations when primitives cannot be used. The main situation is when you want to store primitives in one of the Java collections (which cannot handle primitives).

The use of the wrapper classes is greatly simplified by something called autoboxing. This means that Java automatically determines whether a primitive or a corresponding wrapper should be used. So it’s rare that you need to use the wrapper classes explicitly.


ArrayList<Integer> al = new ArrayList<Integer>();

Integer is the wrapper for int. Thanks to autoboxing you can now store ints in the above Arraylist. Or rather Java will perform all necessary conversions back and forth between Integer and int.

Reason of using Wrapper Classes:

1) It is sometimes easier to deal with primitives as objects.
2) Moreover most of the collection classes store objects and not primitive data types.
3) The wrapper classes provide many utility methods also.
Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.



The word Polymorphism means of many forms.In programming this word is meant to reuse the single code multiple times. In object oriented programming its a big question that why the Polymorphism is done, what is the purpose of it in our code?

There are lots of people who don’t even know the purpose and usage of Polymorphism.Polymorphism is the 3rd main pillar of OOP without it the object oriented programming is incomplete. Lets go in the depth of Polymorphism.

Why Polymorphism is done in OOP?

Its obvious that when we do inheritance between two classes, all the methods and properties of the first class are derived to the other class so that this becomes the child class which  adobes all the functionality of base class.It can also possesses its own separate methods.

But there is a big problem in inheriting the second class to the first class as it adobes all the methods same as the base class has,which  means that after inheritance both(base class& child class) have the methods of same name and same body as shown in this example:~
Base class:
public class fish
  public void eat()
        console.writeline("fish eat");
  public void swim()
          console.writeline("fish swim");
Derieved Class:
class Dolphen:fish

  public void eat()
        console.writeline("fish eat");
  public void swim()
          console.writeline("fish swim");
In this example it is clear that when we Inherit two classes, all the methods with the same name and same body are adobed by the derived class as shown above.Both methods have the same name but if we change the body of the second method then it makes Compiler disturb whether to compile base class method or derived classes.
To remove this problem and to tell the compiler that which method is to be executed we need to use Polymorphism.

How the Polymorphism is done?

Polymorphism is used to remove the problem which is shown in the above code.It is done not by changing the name of the methods of both base & derived class.Infect it is done by adding the “virtual” keyword before the base class method, and the “override” keyword before the derived class method.As shown in this exmple:
Base Class:
public class fish
            public virtual void eat()
                Console.WriteLine("fish eat");
            public virtual void swim()
                Console.WriteLine("fish swim");
 Derived Class:

class Dolphin : fish

            public override void eat()
                Console.WriteLine("Dolphin can eat");
            public override void swim()
                Console.WriteLine("Dolphin can swim");
This is actually the Polymorphism in which we write virtual keyword with the base class method and we write override keyword with the derived class method as we did. It helps the compiler to select the method to be executed.
Here is the complete code in which Polymorphism has been applied.
class Program
        public class fish
            public virtual void eat()
            {  }
            public virtual void swim()
            { }
            public virtual void dive()

       public class Dolphin : fish
            public override void eat()
            { Console.WriteLine("Dolphin eats Plants"); }
            public override  void swim()
            { Console.WriteLine("Dolphin swims quickly"); }
            public override  void dive()
            { Console.WriteLine("Dolphin dive deeply "); }
           public void dance()
            { Console.WriteLine("Dolphin can Dance"); }

        public class Shark : fish
            public override  void eat()
            { Console.WriteLine("Shark eats dead animal"); }
            public override  void swim()
            { Console.WriteLine("Sharks swim fastest than Dolphin"); }
            public override  void dive()
            { Console.WriteLine("Sharks Dive deeper than Dolphin"); }

            public void kill()
            { Console.WriteLine("Shark kills Others"); }


        static void Main(string[] args)
            Dolphin D = new Dolphin();
            Shark S = new Shark();
Types of Polymorphism:
In general there are three types of polymorphism:
Overloading polymorphism:

Overloading polymorphism is where functions of the same name exist, with similar functionality, in classes which are completely independent of each other (these do not have to be children of the object class). For example, the complex class, the image class and the link class may each have the function “display”. This means that we do not need to worry about what type of object we are dealing with if all we want to do is display it on the screen.

Parametric polymorphism:

Parametric polymorphism is the ability to define several functions using the same name, but using different parameters (name and/or type). Parametric polymorphism automatically selects the correct method to be adopted according to the type of data passed in the parameter.

We can therefore define several addition() methods using the same name which calculates a sum of values.

  • The int addition(int,int) method would return the sum of two integers.
  • The float addition(float, float) would return the sum of two floats.
  • The char addition(char, char) would result as the sum of two characters as defined by the author.
  • etc.

signature is the name and type (static) given to the arguments of a function. Therefore it is a method’s signature which determines what is called on.

Inclusion polymorphism:

The ability to redefine a method in classes that are inherited from a base class is called specialization. One can therefore call on an object’s method without having to know its intrinsic type: this is inclusion polymorphism. This makes it possible to disregard the specialized class details of an object family, by masking them with a common interface (this being the basic class).

Imagine a game of chess, with the objects kingqueenbishopknightrook and pawn, each inheriting thepiece object.
The movement method could, using inclusion polymorphism, make the corresponding move according to the object class that is called on. This therefore allows the program to perform piece.movement without having to be concerned with each piece’s class.



Inheritance is specific to object-oriented programming, where a new class is created from an existing class. Inheritance (often referred to as subclasses) comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. The main advantage of inheritance is the ability to define new attributes and new methods for the subclass which are then applied to the inherited attributes and methods. This can be used to create a highly specialized hierarchical class structure. The biggest advantage is that there is no need to start from scratch when wanting to specialize an existing class.

In inheritance where objects are defined by classes can inherit attributes and behavior from pre-existing classes called baseclasses, superclasses, or parent classes. The resulting classes are known as derived classes, subclasses, or child classes. The relationships of classes through inheritance give rise to a hierarchy.

Subclasses and super classes:

subclass or child class is a derivative class that inherits one or more languages entities from one or more other classes (called superclassesbase classes, or parent classes). The semantics of class inheritance vary from language to language, but commonly the subclass automatically inherits the instance variable and member functions of its superclasses. Some languages support the inhertance of other construct as well.

Class hierarchy:

The parent-child relationship between classes can be represented in a hierarchical view often called class tree view. The class tree view starts with a general class called superclass. Derived classes (child class or subclass) become more specialized further down the tree.

Multiple inheritance:

Some object oriented languages, such as C++ allow multiple inheritance, meaning that one class can inherit attributes from two superclasses. This method can be used to group attributes and methods from several classes into one single class.


Inheritance and controlling access:

You control access to variables, classes, functions, and methods using access control attributes.

Table1. Access control attributes

Access control attribute keyword Access
public available to any caller
private available only to the class that defines it
protected available only to the class that defines it and to any subclasses of that class
internal available to any caller within the same package

Methods that cannot be overridden:

Just as classes may be sealed/finalized method declarations may contain method modifiers that prevent the method from being overridden (i.e. replaced with a new function with the same name and type signature in a subclass). A private method is unoverridable simply because it is not accessible by classes other than the class it is a member function of.


Many object-oriented programming languages permit a class or object to replace the implementation of an aspect—typically a behavior—that it has inherited. This process is usually called overriding.

Overriding introduces a complication that which version of the behavior does an instance of the inherited class use—the one that is part of its own class, or the one from the parent (base) class? The answer varies between programming languages, and some languages provide the ability to indicate that a particular behavior is not to be overridden and should behave as defined by the base class.

Inheritance vs subtyping:

Subtyping enables a given type to be substituted for another type or abstraction. Subtyping is said to establish an is-a relationship between the subtype and some existing abstraction, either implicitly or explicitly, depending on language support. The relationship can be expressed explicitly via inheritance in languages that support inheritance as a subtyping mechanism. For example, the following C++ code establishes an explicit inheritance relationship between classes B and A, where B is both a subclass and a subtype of A, and can be used as an A wherever a B is specified (via a reference, a pointer or the object itself).

class A 
{ public:
   void DoSomethingALike() const {}

class B : public A 
{ public:
   void DoSomethingBLike() const {}

void UseAnA(A const& some_A)

void SomeFunc()
   B b;
   UseAnA(b); // b can be substituted for an A.

In programming languages that do not support inheritance as a subtyping mechanism, the relationship between a base class and a derived class is only a relationship between implementations (a mechanism for code reuse), as compared to a relationship between types. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entail behavioral subtyping. It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected.

Object Oriented Programming

Chapter 4: Grouping objects

  •  Class libraries
  • Arrays List
  • Loops
  • While loop
  • For loop
  • Iterators
  • Has next
  • Next
  • Index access versus iterators




  • Inheritance
  • Super class and sub class
  • Inheritance hierarchies
  • Coding of inheritance
  • Inheritance and access-rights
  •  Inheritance and initialization
  • Advantages of inheritance
  •  Avoiding code duplication
  •  Code reuse
  •  Easier maintenance
  • Extendibility
  • Subtyping
  • Subclasses and subtypes
  • Subtyping and assignment
  • Polymorphic variables
  • Polymorphic collections
  • Element types
  • Casting revisited
  • Wrapper classes 


  • Static type and dynamic type
  • Overriding
  • Dynamic method lookup
  • Super call in methods
  • Method polymorphism
  • Object methods: toString
  • Protected access