ch6 - Classes and Wrapper Classess
ch6 - Classes and Wrapper Classess
ch6 - Classes and Wrapper Classess
PDCA-201
Unit-3. Lesson - 6
Chapter Index
Objectives
Introduction
Defining a Class
Adding Variables
Adding Methods
Creating Objects
Accessing Class Members
Constructors
Inheritance
Extending a Class
Defining a subclass
Subclass constructor
Multilevel inheritance
Hierarchical inheritance
Overriding Methods
Final Variables and Methods
Final Classes
Finalizer Methods
Wrapper Classes
Autoboxing and Unboxing
Static Classes
Abstract Classes
Enumerated types and annotations
Method Overloading
Nesting of methods
Methods with varargs
Garbage Collection
Summary
Glossary
Answers to Check Your Progress / Self Assessment Questions
References / Suggested Readings
Model Questions
Objectives
Understanding the meaning and significance of Classes and Objects.
Demonstrates the use of constrcutors.
Explain the concept of inheritance and different types of inheritance.
Explain the concept of method overloading and method overriding.
Explain the concept of Garbage Collection.
Demonstrate the use of wrapper classes.
Introduction
Classes are the basic building blocks of a Java program. A class is like a structure or template that is
used to create objects. A class contains attributes and behaviour. The attributes are represented by
variables and the behavior is represented by methods. A class can also be treated as a new user-
defined data type that is created from the Java inbuilt primitive data types.
As shown in the above class definition, the body of a class usually consists of instance variable and
methods.
6.1.1 Adding Variables
The variables declared within a class also called instance variables. The data types of instance
variables can be of any primitive data types such as int, char, float, double etc. or can be a reference
type such as an object, array, string etc. You can define a class containing only member variables as
shown below:
class Student
{
int rollno ;
String name ;
double marks ;
}
The class Student mentioned contains three instance variables, rollno, name and marks.
void percentage( )
{
double percent ;
percent = marks / 800 * 100 ;
System.out.println("The percentage is "+percent) ;
}
}
Declare a variable of class type known as reference variable. The reference variable refers to an
object of that class. At this point, the reference variable contains the value null that means , it
does not point to any object yet.
Create an object using new operator and assign that object to a reference variable. The operator
new dynamically allocates memory for an object at runtime and returns a reference to it. In Java,
objects are manipulated through object references.
For Example
Student ob ;
ob = new Student ( ) ;
This statement assigns a value of 5209 to instance variable rollno within the object ob.
Here is an example that demonstrates writing a class, creating objects of that class and accessing its
members to initialize them using a dot operator.
class Student
{
// Declaring instance variables
int rollno ;
String name ;
double marks ;
public static void main(String args[ ])
{
Student ob = new Student( ) // Creating an object
6.4 Constructor
An object should be first initialized before using it in a program. In order to initialize an object, each
member variable of that object is initialized with some value. It is difficult to initialize all of the
variables in a class each time an object is created. For this purpose, constructor is used to perform the
initialization of variables upon creation of an object. A constructor is a special form of a method and is
invoked automatically and immediately when an object is created using new operator. However, there
are some restrictions using a constructor:
A constructor must have the same name as the name of the class.
A constructor does not return anything by default, so no return type should be used, not even
void.
A class may have any number of constructors, this is called constructor overloading.
Every class has a default constructor. If we do not explicitly design a constructor for a class,
the java compiler builds a default constructor for that class.
For example:
class Student
{
int rollno ;
String name ;
double marks ;
6.5 Inheritance
Inheritance is an important principle of OOP that enables the reuse of code. In this mechanism, one
class (subclass) can inherit all of the instance variables and methods of another class (superclass).
With the help of an inheritance, a class immediately has all the functionality of a superclass and the
new subclass has to incorporate only those things that are not present in the superclass. During
creating inheritance hierarchy, at the root level, a general class is created that contains common
attributes. This class can then be inherited by other more specific classes, each of them, adding
specific things that are unique to it. Thus, using inheritance, one need to be start from scratch.
The inheritance relationship can be shown in Fig. 6.1 using the UML class diagram using a solid line
with an arrow head pointing towards super class name.
.
Superclass
Subclass
class SuperClass
{
double a ;
double b ;
SuperClass(double m, double n)
{
a=m;
b=n;
}
void print()
{
System.out.println(a + " " + b) ;
}
}
void mean( )
{
double result ;
result = (a + b+ c ) / 2 ;
System.out.println("Mean = "+ result) ;
}
}
class ConstructorDemo
{
public static void main(String args[])
{
SuperClass sup = new SuperClass(25,37) ;
sup.print() ;
Multilevel Inheritance
In Java, hierarchies that consists of unlimited layers of inheritance can be created. So, you can create a
subclass of a class which is also a subclass of another class and so on. For example, if a class Child
inherits from class Parent, and class Parent inherits from class GrandParent, then the class Child
will acquire all the members defined in class Parent as well as all the members declared in class
GrandParent. The multilevel inheritance is shown in Fig. 6.2 given below.
GrandParent
Parent
Child
Figure 6.2 Diagram showing multilevel inheritance
Hierarchical inheritance
In hierarchical inheritance, many subclasses inherit from a single superclass. For example, if classes
Child1, Child2 and Child3 inherit from same class Parent, then classes Child1, Child2 and Child3
will acquire all the members from the class Parent. The hierarchical inheritance is shown in Fig. 6.3
given below.
Parent
Overriding Methods
Method overriding occurs when a subclass method has the same name and type signature as a method
in its superclass. The return types of both methods must be the same. When an overridden method is
invoked by the object of subclass, it will always refer to the version of a method defined by the
subclass. This can be demonstrated with the help of an example.
class SuperClass
{
double a ;
double b ;
SuperClass(double m, double n)
{
a=m;
b=n;
}
void mean( )
{
double result ;
result = (a + b ) / 2 ;
System.out.println("SuperClass Mean = "+ result) ;
}
}
class SubClass extends SuperClass
{
double c ;
SubClass(double m, double n, double o)
{
super(m,n) ;
c=o;
}
void mean( )
{
double result ;
result = (a + b+ c ) / 2 ;
System.out.println("SubClass Mean = "+ result) ;
}
}
class ConstructorDemo
{
public static void main(String args[])
{
SuperClass sup = new SuperClass(25,37) ;
sup.mean() ;
SubClass sub = new SubClass(45,87,63) ;
sub.mean() ;
}
}
Final classes prevent inheritance and thus, cannot be inherited. When a class is declared as final, all of
its methods are implicitly declared as final. To declare a final class, use the modifier at the beginning.
Finalizer Methods
Finalizer Methods are used in a garbage collection mechanism, in which the objects are automatically
destroyed when no reference of that object exist and the memory occupied by that object is reclaimed.
Sometimes, an object eligible for garbage collection occupies some resources such as file or database
connection for reading or writing purpose, then those resources must be released before the object is
destroyed. For this purpose, Java provides a mechanism called finalization. You can add a finalizer in
your class by simply define the finalize( ) method. Java run time calls this method automatically,
whenever the object of that class is about to destroy. The syntax of the method is:
Wrapper Classes
Java uses simple data types such as byte, short, char, int, float, double and boolean that cannot be
treated as objects. Sometimes, an object representation of these types is required so as to perform
various operations. For this purpose, Java Provides wrapper classes corresponding to each of these
simple types. All the wrapper classes reside in java.lang package and its hierarchy is depicted in Fig.
6.4.
Object
Number
The term boxing refers to automatic conversion of primitive type to an object of corresponding
wrapper class such as int to java.lang.Integer. Conversely, unboxing refers to conversion of wrapper
object to its equivalent primitive type such as Integer to int. The boxing and unboxing occurs in
assignment expressions, mathematical expressions and methods. For example:
public class BoxingDemo
{
public static void main(String args[ ])
{
Double d = 15.25; // boxes double to Double object
d = d + 20.20 ; // unboxes the Double to a double
System.out.println("Double value : "+d);
}
}
Static Classes
A static class is created inside another class is called static inner class. The static inner class can
access only static variable and methods of its outer class including private. We cannot create an object
of static inner class without the reference of outer class. This can be illustrated with the help of an
example:
class Outer
{
static int i = 95;
static class Inner
{
void print( )
{
System.out.println("Value of i ="+i) ;
}
}
}
class Test
{
public static void main(String args[])
{
Outer.Inner ob = new Outer.Inner( ) ;
ob.print() ;
}
}
Abstract Classes
Abstract classes are partially completed classes and contain one or more abstract methods. The
abstract methods are non-implementing methods having no body. An object of an abstract class cannot
be created but we can declare a reference variable of an abstract class. Any subclass of an abstract
class must either implement all of the abstract methods from the abstract class or declare itself as an
abstract too. An abstract class may also contain non-abstract methods. To declare a class abstract, the
abstract modifier is used with the name of the class. The syntax is:
Method Overloading
In Java, different methods with the same name but different signature can be defined and is known as
method overloading. The signature of methods includes the number and/or type of parameters. The
difference in return types alone is not sufficient for the methods to be overloaded. Method overloading
implements polymorphism. Whenever, an overloaded method is called, Java run time search for a
matching method based on arguments supplied at the time of the method call, to determine which
version of the overloaded method is to be invoked. This can be illustrated with the help of an example:
class Overloading
{
void max(int a, int b)
{
int big ;
if(a > b)
big = a ;
else
big = b ;
System.out.println("Maximun of two integer values = " + big) ;
}
void max(double a, double b)
{
double big ;
if(a > b)
big = a ;
else
big = b ;
System.out.println("Maximun of two double values = " + big) ;
}
}
class OverloadingDemo
{
public static void main(String args[])
{
Overloading ob = new Overloading( ) ;
ob.max(6,19);
ob.max(45.2, 34.5) ;
}
}
Nesting of Methods
When a method in a class invokes another method within the same class, it is known as nesting of
methods. In order to call a method in the same class, dot(.) operator is not required. It is possible to
call more than one method in the same class. This can be demonstrated with the help of an example:
class NestingMethod
{
int a ;
int b ;
int big ;
void max(int a, int b)
{
if(a > b)
big = a ;
else
big = b ;
display( ) ;
}
void display( )
{
System.out.println("Maximun of two integer values = " + big) ;
}
}
class NestingMethodDemo
{
public static void main(String args[])
{
NestingMethod ob = new NestingMethod( ) ;
ob.max(16,19);
}
}
Garbage Collection
Ques 14. What is the difference between method overloading and method overriding?
Ques 15. Which method is used to run a garbage collector?
Glossary
Class : a structure or template consisting of variables and methods.
Object: physical implementation of a class.
Abstract classes : partially implemented class containing abstract methods.
Method overloading :Methods having the same name but with different parameters
Method overriding : Methods with same name and parameters.
Garbage collection: Mechanism for destroying unused objects.
}
Ans 7. With the help of actual arguments supplied at the time of method call.
Ans 8. No
Ans 9. Final
Ans 10. Perform tasks to release the resources captured by unused object.
Ans 11. Java.lang.Integer.
Ans 12. No
Ans 13. No
Ans 14. More than one method having same name but with different parameters is called method
overloading. More than one method with the same name and parameters is called method overriding.
Ans 15. void gc( )
References / Suggested Readings
1. Complete Reference Java, Tata McGraw Hill.
2. Java A Beginner's Guide, Herbert Schildt Oracle Press
3. Core Java Volume I — Fundamentals (9th Edition), Prentice Hall
4. Programming Using Java, Meenu Sareen, Jyoti Book Depot, Jallandhar, India.
Model Questions
1. What is the difference between an application and an applet?
2. How can an applet embedded in a web document.
3. What is the use of <head> section in html language?
4. What is the difference between signed and unsigned applets?
5. What are various advantages of applets in java?