ch6 - Classes and Wrapper Classess

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Classes and Wrapper Classes

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.

6.1 Defining a Class


A class consists of variables and methods that operate on variables.The variables contain data and the
methods contain the code to process the data stored in variables. The variables and methods are
collectively known as class members.A class is declared using the keyword class followed by the
name of that class. The general form of a class definition is given below:
class ClassName
{
type varname_1 ;
type varname_2 ;
……………….
……………….
type varname_N ;

return_type methodname_1(type var_1, type var_2,…,type var_N)


{
<method body>
}
return_type methodname_2(type var_1, type var_2,…,type var_N)
{
<method body>
}
:
:
return_type methodname_N(type var_1, type var_2,…,type var_N)
{
<method body>
}
}

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.

6.1.2 Adding Methods


A class can be declared that contains only instance variables, but it limits the applicability of the class.
To increase the power and flexibility of a class, method is put in the class. A method contains code
that operates on instance variables and is used to perform a specific task.The return_type specifies the
type of data returned by the method. The return type can any valid data type or class type. If a method
does not return any value, the return type should be of type void. The method_nameis any valid user-
defined name assigned to a method. The variables (type var_1, type var_2,…,type var_N ) are the
parameters that receive the value of the arguments at the time of calling the method. The parameter list
can be left blank, if a method does not require any value. Also, if a method have a return type other
than void, the method must contain a return statement of the form:
return result ;
Here, the result is the value to be returned.
For example, the class Student as shown above is extended and contains a method percentage( ) as
illustrated below:
class Student
{
int rollno ;
String name ;
double marks ;

void percentage( )
{
double percent ;
percent = marks / 800 * 100 ;
System.out.println("The percentage is "+percent) ;
}
}

6.2 Creating Objects

An object is a physical implementation a class and is known as an instance of a class.


Creating objects of a class is a two-step process:

 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 ( ) ;

Check Your Progress / Self Assessment Questions


Ques 1. What is the difference between a class and object?
Ques 2. Which operator is used to create an instance of a class?

6.3 Accessing Class Members


Once an object of a class is created, its instance variables occupy memory and needs to be initialized.
The members of a class(variables and methods) can be accessed using the dot operator (.) with the
name of the object and then name of class member to be accessed. For example, the following
statements declare the Student object and access the member rollno of the object ob.
Student ob = new Student( )
ob.rollno = 5209 ;

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

// assign values to data members.


ob.rollno = 5209;
ob.name = "Rahul Sharma" ;
ob.marks = 589;
double result ;
result = ob.marks / 800 * 100 ;
System.out.println("The percentage is "+result) ;
}
}

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 ;

Student(int r, String n, double m)


{
rollno = r ;
name = n ;
marks = m ;
}
double percentage( )
{
double result ;
result = marks / 800 * 100 ;
return result ;
}
}
class studentDemo
{
public static void main(String args[ ])
{
Student ob1,ob2 ;
ob1 = new Student(5673,"SandeepSood",575) ;
System.out.println("The Percentage of "+ob1.name+" is " + ob1.percentage( )) ;

ob2 = new Student(6145,"Sanjay Sareen",602) ;


System.out.println("The Percentage of "+ob2.name+" is " + ob2.percentage( )) ;
}
}

Check Your Progress / Self Assessment Questions

Ques 3. Which operator is used to access a class member?


Ques 4. What is purpose of a constructor?

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

Figure 6.1 UML diagram showing inheritance

6.6 Defining a Subclass


A subclass can be created using the keyword extends. All the members except private members are
automatically inherited in the subclass. The syntax to create a subclass is:
class subclass_name extends superclass_name
{
// members that are specific to subclass and are not persent in superclass
}
Here, the superclass is parent class that already exists.

6.7 Subclass Constructor


A subclass inherits all of the public members of the superclass, it does not inherit constructors.
Therefore, the objects of subclass cannot be created and initialized using the constructor of its
superclass. The subclass require its own constructor in order to initialize objects. The constructor of
superclass can be invoked within the constructor of subclass using the keyword super. The super
statement must be the first statement in the subclass constructor.

Let’s take an example to illustrate the use of constructors in inheritance:

class SuperClass
{
double a ;
double b ;
SuperClass(double m, double n)
{
a=m;
b=n;
}
void print()
{
System.out.println(a + " " + b) ;
}
}

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("Mean = "+ result) ;
}
}

class ConstructorDemo
{
public static void main(String args[])
{
SuperClass sup = new SuperClass(25,37) ;
sup.print() ;

SubClass sub = new SubClass(45,87,63) ;


sub.print() ;
sub.mean() ;
}
}

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

Child1 Child2 Child3

Figure 6.3 Diagram showing hierarchical inheritance

Check Your Progress / Self Assessment Questions

Ques 5. What is the use of inheritance?


Ques 6. What is the syntax of creating a subclass from a superclass ?

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 Variables and Methods


A final variable is a named constant whose value cannot be modified during the execution of the
program. Thus, the final variables must be initialized at the time of declaration. Final variables do not
occupy memory upon creation of different objects. It is a common convention to use uppercase
identifiers to represent final variables. The variable can be declared final using the modifier final
before the type specifier. For example final int MAX_MARKS = 1200.
Final methods cannot be overridden. It means when you define a final method in a superclass, its
subclass cannot override that method in its own class. Methods can be declared final using the
modifier final at the start of its declaration. For example

final void area( )


{
// Method body
}
Final Classes

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.

final class Test


{
void print( )
{
System.out.println(“This is a final method by default”) ;
}
}

Check Your Progress / Self Assessment Questions

Ques 7. How it will decide, which version of method is to be invoked?


Ques 8. Can we override the final methods?
Ques 9. Which keyword is used to declare final variables?

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:

protected void finalize( )


{
//code here
}

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

Character Byte Short Integer Long Float Double Boolean

Figure 6.4 Hierarchy of Wrapper classes

Autoboxing and Unboxing

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);
}
}

Check Your Progress / Self Assessment Questions

Ques 10. What is the use of finalize( ) method?


Ques 11. What is the name of wrapper class for integer?

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:

abstract class AbstractClassName


{
abstract void print( ) ; // abstract method
void display( )
{
// code here
}
}

Check Your Progress / Self Assessment Questions

Ques 12. Can a static class access non-static members?


Ques 13. Can abstract class contain instance methods?

Enumerated types and annotations

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);
}
}

Methods with varargs

Garbage Collection

Garbage collection is a mechanism of destroying objects automatically when no reference variable


exists containing the reference of that object and reclaiming the memory occupied by the object. It
provides optimum utilization of memory. The Java run time periodically initiate the method void gc( )
of the class Runtime to initiate garbage collection to recycle unused objects.

Check Your Progress / Self Assessment Questions

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.

Answers to Check Your Progress / Self Assessment Questions


Ans 1. A class is a structure or blueprint of the object, whereas an object is the physical
implementation of a class.
Ans 2. New operator
Ans 3. Dot(.) operator
Ans 4. A constructor is used to initialize the state of an object.
Ans 5. Reusability of existing code.
Ans 6. class subclass extends superclass
{

}
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?

You might also like