You are on page 1of 2

M.

Wahab Khan
4001-FBAS/BSCS/F18-B
******************************************************************

Q. Compare and contrast abstract classes and wrapper


classes in Java?
Ans.

Abstract Class Wrapper Class


Abstract class is a restricted class that Wrapper classes provide a way to use
cannot be used to create objects (to primitive data types (int, boolean, etc.)
access it, it must be inherited from as objects.
another class).
The abstract keyword is a non-access The table below shows the primitive
modifier, used for classes and methods. type and the equivalent wrapper class:
An abstract class can have both Primitive Data type Wrapper Class
abstract and regular methods: byte Byte
//abstract class short Short
abstract class Animal int Integer
{ long Long
//abstract method float Float
public abstract void animalsound(); double Double
//regular method boolean Boolean
public void sleep() { char Character
System.out.println(“zzz”);
}
}
From the example above, it is not Sometimes we must use wrapper classes, for
possible to create an object of the example when working with Collection
objects, such as Arraylist, where primitive
Animal class:
types cannot be used (the list can only store
Animal myObj = new Animal(); objects):
//will generate an error ArrayList<int>myNumbers=new
ArrayList<int>(); //Invalid
ArrayList<Integer>myNumbers=new
ArrayList<Integer>(); //Valid
Abstract Class Wrapper Class
Use: To create a wrapper object, use the wrapper
To achieve security – hide certain class instead of the primitive type. To get the
value, we can just print the object:
details and only show the important
Public class Main {
details of an object. Public static void main(String[ ]args
To access the abstract class, it must be {
inherited from another class. Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = ‘A’;

System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}

****************************************************************

You might also like