You are on page 1of 23

9

2 INTRODUCTION TO CLASSES

2.1 Class fundamentals


2.2 Declaring objects
2.3 Assigning object reference variables
2.4 Introducing methods
2.5 Constructors
2.6 The this keyword
2.7 Garbage collection
2.7.1 The finalize method
2.8 Wrapper class

2.1 Class fundamentals


Class is a user defined data type that allows you to bind data and its
associated code together in a single unit.
When you are defining a class you are actually creating a new data type.
Using this newly created data type you can create a variable of its type
which is known as object. Thus object is a variable of type class.
Thus in the relationship of class and object a class acts as a template for
an object which contains variables and methods, and an object acts as an
instance of a class that access variables and methods defined inside the
class.
The General Syntax of a defining a Class is given below:
class ClassName
{
Data type instance-variable1;
Data type instance-variable2;
………………………………………………
………………………………………………
Data type instance-variableN;
Return type MethodName1 (Parameter-list)
{
}

1|Page
Return type MethodName2 (Parameter-list)
{
}
……………………………………………………………………..
……………………………………………………………………..
Return type MethodNameN (Parameter-list)
{
}
}
The class can be created using the keyword class.
The class contains two things:
(1) Variable Declaration
(2) Function Definition
The variables that are defined within a class are known as instance
variables.
The functions defined inside the class are known as methods.
The methods and Instance variables defined inside a class are called
members of the class.
While declaring instance variables and defining methods inside the class
you can also specify access specifier for them such as public, private and
protected. By default members of the class are public.
Example:
Lets create a class named Rectangle that contains two instance variable
named length and width and one method area () as follow:
class Rectangle
{
double length;
double width;
double area ()
{
return length*width;
}
}

2|Page
In the above example by defining the class you have created a new data
type called Rectangle. Now using this new data type we can create a
variable of that type which is known as object.
When we declare the class memory is not allocated to the instance
variables of the class because class declaration just acts as a template. In
order to allocate memory to the instance variable we have to create an
object of type class Rectangle as shown below:
Rectangle R1 = new Rectangle ();
Here, R1 is the object or instance of class Rectangle. When we create
object memory is allocated to the instance variables of the class. For each
object of the class memory is allocated separately.
Once you create an object of the class you can access instance variables
and method of the class using object name followed by dot operator
followed by instance variable or method as follow:
ObjectName.InstanceVariable= Value;
ObjectName.MethodName ();
Example:
R1.length = 35;
R1.width = 56;
Consider the Following example that calculate Area of Rectangle:
class Rectangle
{
double length;
double width;
void setValue(double l, double w)
{
length=l;
width=w;
}
double area()
{
return length*width;
}
}
class Test

3|Page
{
public static void main (String args[])
{
Rectangle R1 = new Rectangle ();
R1.setValue (35, 42);
System.out.println ("Area of Rectangle= " + R1.area ());
}
}
2.2 Declaring objects
When you create a class, you are creating a new data type. Using this
newly created data type you can declare a variable of its type which is
known as object.
In order to declare an object of type class you have to follows two simple
steps as mentioned below:
Step 1: Declare a variable of type class using following syntax:
ClassName ObjectName;
Example:
Rectangle R1;
Here, R1 is a variable of type class Rectangle that refers to the
object.
Step 2: Allocate memory to the object using following syntax:
ObjectName = new ClassName ();
Example:
R1 = new Rectangle ();
Here, new operator is used to allocate memory space for the
object at run time and Rectangle () is a default constructor of the
class that initializes data members of the class with default value.
You can also combines above two steps into single step using following
syntax to create an object:
ClassName ObjectName = new ClassName ();
Example:
Rectangle R1 = new Rectangle ();
2.3 Assigning object reference variables
 In Java it is possible to create an object of the class that contains
reference of the object of the same class that is created previously.

4|Page
 Consider the following example:
Rectangle R1 = new Rectangle ();
Rectangle R2 = R1;
 In the above example first you have create an object R1 of type class
Rectangle and allocate actual physical memory to that object. Which shown
graphically in the below figure:

 In the second statement you just declare another variable R2 of type class
Rectangle but it is not allocated any actual physical memory. It is just
assigned reference of the object that is previously created. Thus the object
R2 contains an address of the object R1. Which is shown graphically in the
below figure:

 Thus object R1 and R2 refers to the same memory location. Object R2


contains reference of object R1. You can use object R1 and R2
interchangeably to refer to the same memory location.
 If you change the value of the data member of class Rectangle using R1
and retrieve its value using R2 then you will get the value that is modified
using object R1.

5|Page
 If you assign null value to object R1 then still object R2 refers to the same
memory location that is assigned to it.

 Consider the Following example:


class Rectangle
{
double length;
double width;
void setvalue(double l, double w)
{
length=l;
width=w;
}
double area()
{
return length*width;
}
}
class RectangleDemo1
{
public static void main (String args [])
{
Rectangle R1 = new Rectangle ();
Rectangle R2=R1;
R1.setvalue (3, 4);
R2.setvalue (2, 5);
System.out.println ("Area of Rectangle= " + R1.area ());
System.out.println ("Area of Rectangle= " + R2.area ());
}
}
Output:

2.4 Introducing methods

6|Page
 A function that is defined inside the class is known as method.
 The general syntax of defining method inside the class is given below:
ReturnType MethodName (Parameter-list)
{
// body of method
}
Here,
ReturnType indicates the type of the value that is returned by the
method. It can be any data type including void. If the method does not
return any value then you must specify the return type as void. If the
return type of the method is not void then the method must explicitly
return a value of specific type using return statement.
MethodName is the name of the method.
Parameter-list is the sequence of Data Type variable pair separated by
comma. If method does not accept any parameter then it should be left
blank.
Once you define method inside class you can call this method using object
of the class as shown below:
ObjectName.MethodName (Parameter List);
Here,
Parameter List is the sequence of values separated by comma. The
values in the Parameter List must match in number and in type with the
Parameters that are specified at the time of defining the method. Any
violation in matching parameters generates a compile time error.
Consider the Following example that calculate Area of Rectangle:
class Rectangle
{
double length;
double width;
void setValue(double l, double w)
{
length=l;
width=w;
}
double area()
{
return length*width;
}
}
class RectangleDemo1

7|Page
{
public static void main(String args[])
{
Rectangle R1 = new Rectangle ();
R1.setvalue (3, 4);
System.out.println ("Area of Rectangle= " + R1.area ());
}
}
Output:

2.5 Constructors
Constructor is a special method of the class because its name is same as
the class name.
Constructor constructs the value for the instance variable of the class. The
task of the constructor is to initialize all the instance variables of the class
each time an object of that class is created.
Constructor is invoked automatically when the object of its associated class
is created.
Constructor does not have any return type not even void because the
implicit return type of constructor is class in which it is declared.
If you does not define any constructor in your class even there is one
constructor available in the class which is known as the default constructor
of the class which initializes instance variable of the class with default
values.
Consider following example in which we are using Rectangle as a
constructor to set value of length and width when create object of class
Rectangle.
class Rectangle
{
double length;
double width;
Rectangle ()
{
length=5;
width=6;
}
double area()
{
return length*width;

8|Page
}
}
class RectangleDemo1
{
public static void main(String args[])
{
Rectangle R1 = new Rectangle ();
Rectangle R2 = new Rectangle ();
System.out.println ("Area of Rectangle= " + R1.area ());
System.out.println ("Area of Rectangle= " + R2.area ());
}
}
Output:

In above example class Rectangle has one constructor Rectangle. When


you create an object R1 using following statement:
Rectangle R1 = new Rectangle ();
Constructor is called and initializes instance variable length and width.
Each time an object is created constructor is called thus when you create
object R2 constructor is called again and initializes instance variable length
and width.
Now, R1.area () call area () method of class Rectangle and give output
calculation of length*width which is 30.Because for R1 value of length is
5 and value of width is 6.
Same way R2.area () call area () method of class Rectangle and give
output calculation of length*width which is 30.Because for R2 value of
length is 5 and value of width is 6.
One disadvantage of this type of constructor is that each time you create
an object of the class its instance variables are assigned same value. If
you want to initialize instance variables of different object with different
values then it is not possible using this constructor.
This can be achieved using another form of constructor which is called
parameterized constructor.
 Parameterized Constructor:

9|Page
A Constructor which takes parameter as an argument is known as
Parameterized Constructor. Using Parameterized Constructor it is possible
to assign different values for the instance variables of different objects.
In order to do so you need to pass values for the instance variable of the
class at the time of creating object as shown below:
Rectangle R1 = new Rectangle (2, 4);
Here, value for the instance variables length and width is passed as an
parameter to the constructor Rectangle ().
Now consider the above example with parameterized constructor as shown
below:
class Rectangle
{
double length;
double width;
Rectangle (double l, double w)
{
length=l;
width=w;
}
double area()
{
return length*width;
}
}
class RectangleDemo1
{
public static void main(String args[])
{
Rectangle R1 = new Rectangle (5, 6);
Rectangle R2 = new Rectangle (6, 6);
System.out.println ("Area of Rectangle= " + R1.area ());
System.out.println ("Area of Rectangle= " + R2.area ());
}
}
Output:

2.6 The this keyword


this is a keyword which contains reference of the object for which the
method is called.
In Java this keyword is used for two purposes.

10 | P a g e
(1) To refer the invoking object:
Sometimes it is necessary to refer to the object that invoked the method
inside the definition of the method. We can do so using the concept of this
keyword. Using this we can refer to the object inside method that invoked
the method.
For Example:
Rectangle (double l, double w)
{
this.length=l;
this.width=w;
}
Here, this is useful to refer object that invoke the method.
(2) To prevent Instance variable Hiding:
You can not declare local variable or formal parameter with same name as
instance variable in the method. If you do so then this local variable or
formal parameter will hide the instance variable in the method.
In order to prevent Instance variables from being hiding from local
variables or formal parameters you can use this keyword.
For Example:
Rectangle (double length, double width)
{
this.length = length;
this.width = width;
}

In the above example this.length refers to the instance variable of the


class while length refers to the formal parameter of the method.
2.7 Garbage collection
In programming languages such as C++ and JAVA objects are created
dynamically at run time using the new operator. But the releasing of the
memory for that object is performed quite different in both languages.
In C++ the objects are destroyed using the delete operator whenever
there is no need for that objects. While in JAVA the objects are destroyed
automatically.

11 | P a g e
The technique or utility that automatically destroy the objects from
memory is known as Garbage Collection.
The Garbage Collection works as follow:
When the object(s) are not referenced for a long time in a program it
assumes that there is no need of the object(s) in the program. Garbage
Collection automatically release the memory occupied by that object(s) so
that it can be allocated to the newly created objects.
2.7.1 The finalize method
In JAVA objects are destroyed automatically when they are not referenced
for a long time through Garbage Collection. However sometimes an object
has to perform some action when it is destroyed.
JAVA provides a mechanism called finalization that performs necessary
action when object is about to be destroyed. In order to specify an action
we need to define one method called finalize () in the class.
Finalize () method is called at run time when garbage collector destroy the
object from the memory.
General Syntax of the Finalize () method is given below:
Protected void finalize ( )
{
// action to be performed
}
Here, the method is defined with protected specifier so it can not be
accessed from outside the class.
We can specify the action that needs to be performed in the finalize ()
method.
2.8 Wrapper class
Java has eight basic data types such as byte, short, int, long, float, double,
char and boolean. You can use this basic data types to declare variables.
However you can not create an object of such basic data type.
Sometimes it may be required to create an object of such basic data type.
For example suppose you want to call the method by passing reference of
such basic data type instead of passing its value. At this point you need to
create an object of such basic data type.
Java allows you to do so using the concept of wrapper class. In Java for
each basic data type one separate class is defined which is known as

12 | P a g e
wrapper class. It allows you to represent basic data types in terms of
object.
In Java basically there are three base classes that contains wrapper
classes for basic data types which are mentioned below:
(1)Number Class:
 It is an abstract class.
 It is further derived into six subclasses that contain wrapper classes
to represent numeric data types such as byte, short, int, long, float
and double.
(2)Character Class:
 This class wraps the basic data type char.
(3)Boolean Class:
 This class wraps the basic data type boolean.
The name of each wrapper class is same for its corresponding basic data
types but the first letter of the wrapper class is in Uppercase to distinguish
it from basic data type.
Each wrapper class defines various methods that can be applied to basic
data types.
 Instance Variables common for all Sub class of Number Class:
Name Purpose
MIN_VALUE It returns the minimum value that can be
assigned to the invoking wrapper class object. It
varies based on various wrapper class objects.

MAX_VALUE It returns the maximum value that can be


assigned to the invoking wrapper class object. It
varies based on various wrapper class objects.

SIZE It returns the size of invoking wrapper class


object. It varies based on various wrapper class
objects.

TYPE It returns the basic type of the value represent by


the invoking wrapper class object. It varies based
on various wrapper class objects.

 Methods Common for all Sub class of Number Class:


Method Name Purpose

13 | P a g e
byte byteValue () It returns the byte value of invoking wrapper
class object.
short shortValue () It returns the short value of invoking wrapper
class object.
int intValue () It returns the integer value of invoking wrapper
class object.
long longValue () It returns the long value of invoking wrapper class
object.
float floatValue () It returns the float value of invoking wrapper
class object.
double doubleValue () It returns the double value of invoking wrapper
class object.
int hashCode () It returns the Hash Code of the invoking wrapper
class object.
String toString () It returns the string representation of invoking
wrapper class object that contains decimal
equivalent of the invoking wrapper class object.
boolean equals (Object O) It compares invoking object with object passed as
an argument. If both objects are same then it
returns true otherwise false.
int compareTo (Object O) It compares the value of invoking object with the
value of Object O passed as an argument. It
returns an integer value.
0 = equal
Negative = value of Invoking Object is less then
the value of Object O passed as an argument.
Positive = value of Invoking Object is greater then
the value of Object O passed as an argument.
2.8.1 Byte Class:
This class wraps byte data type byte.
Constructor of Byte Class:
 You can create an object of Byte class using one of the following two
constructor:
(1) Byte (byte value)
(2) Byte (String value)
Example:
Byte b1 = new Byte ((byte) (1));
Byte b2 = new Byte (“12”);

14 | P a g e
Methods of Byte Class:
 Following are the various methods of Byte class:
Method Purpose
compareTo (byte b) It compares the byte value of invoking
Byte object with the byte value of b
passed as an argument. It returns an
integer value.
0 = equal
Negative = value of Invoking Object is
less then passed byte value.
Positive = value of Invoking Object is
greater then passed byte value.
parseByte (String S) It returns a byte value of the number
contained in the string S using default
radix which is 10.
parseByte (String S, int R) It returns a byte value of the number
contained in the string S using radix R.
the default value of radix is 10.
2.8.2 Short Class:
This class wraps basic numeric data type short.
Constructor of Short Class:
 You can create an object of Short class using one of the following two
constructor:
(1) Short (short value)
(2) Short (String value)
Example:
Short S1 = new Short ((short) (1));
Short S2 = new Short (“12”);
Methods of Short Class:
 Following are the various methods of Short class:
Method Purpose
compareTo (short b) It compares the numeric value of
invoking Short object with the short
value b passed as an argument. It
returns an integer value.
0 = equal
Negative = value of Invoking Object is

15 | P a g e
less then passed short value.
Positive = value of Invoking Object is
greater then passed short value.
parseShort (String S) It returns a short value of the number
contained in the string S using default
radix which is 10.
parseShort (String S, int R) It returns a short value of the number
contained in the string S using radix R.
the default value of radix is 10.
2.8.3 Integer Class:
This class wraps basic numeric data type int.
Constructor of Integer Class:
 You can create an object of Integer class using one of the following two
constructor:
(1) Integer (int value)
(2) Integer (String value)
Example:
Integer I1 = new Integer (10);
Integer I2 = new Integer (“12”);
Methods of Integer Class:
 Following are the various methods of Integer class:
Method Purpose
compareTo (int i) It compares the numeric value of
invoking Integer object with the int
value i passed as an argument. It
returns an integer value.
0 = equal
Negative = value of Invoking Object
is less then passed int value.
Positive = value of Invoking Object
is greater then passed int value.
parseInt (String S) It returns an integer value of the
number contained in the string S
using default radix which is 10.
parseInt (String S, int R) It returns an integer value of the
number contained in the string S
using radix R. the default value of

16 | P a g e
radix is 10.
bitCount (int i) It returns the number of one-bits in
the two’s complement
representation of passed integer
value as an argument.
toBinaryString (int i) It returns a string value that
contains the binary equivalent of the
integer value passed as an
argument.
toOctalString (int i) It returns a string value that
contains the octal equivalent of the
integer value passed as an
argument.
toHexString (int i) It returns a string value that
contains the Hexadecimal equivalent
of the integer value passed as an
argument.
numberOfLeadingZeros (int i) It returns total number of leading
zeros in the binary representation of
number I passed as an argument.
The binary number is represented
using 32 bits because the size of an
integer number is 4 byte= 32 bits.
numberOfTrailingZeros (int i) It returns total number of trailing
zeros in the binary representation of
number I passed as an argument.
The binary number is represented
using 32 bits because the size of an
integer number is 4 byte= 32 bits.
rotateLeft (int i, int d) It returns an integer value by
rotating integer number i passed as
an argument to left side by specific
position specified by d. As you
rotate the bits the bits that are
rotated from left side enters into
right side.
rotateRight (int i, int d) It returns an integer value by
rotating integer number i passed as

17 | P a g e
an argument to right side by specific
position specified by d. As you
rotate the bits the bits that are
rotated from right side enters into
left side.
2.8.4 Long Class:
This class wraps basic numeric data type long.
Constructor of Long Class:
 You can create an object of Long class using one of the following two
constructors:
(1) Long (long value)
(2) Long (String value)
Example:
Long L1 = new Long (12);
Long L2 = new Long (“12”);
Methods of Long Class:
 Following are the various methods of Byte class:
Method Purpose
compareTo (long i) It compares the numeric value of
invoking Long object with the long
value i passed as an argument. It
returns an integer value.
0 = equal
Negative = value of Invoking Object
is less then passed long value.
Positive = value of Invoking Object
is greater then passed long value.
parseInt (String S) It returns a long value of the
number contained in the string S
using default radix which is 10.
parseInt (String S, int R) It returns an long value of the
number contained in the string S
using radix R. the default value of
radix is 10.
bitCount (long i) It returns the number of one-bits in
the two’s complement
representation of passed long value

18 | P a g e
as an argument.
toBinaryString (long i) It returns a string value that
contains the binary equivalent of the
long value passed as an argument.
toOctalString (long i) It returns a string value that
contains the octal equivalent of the
long value passed as an argument.
toHexString (long i) It returns a string value that
contains the Hexadecimal equivalent
of the long value passed as an
argument.
numberOfLeadingZeros (long i) It returns total number of leading
zeros in the binary representation of
number i passed as an argument.
The binary number is represented
using 64 bits because the size of an
long number is 8 byte= 64 bits.
numberOfTrailingZeros (long i) It returns total number of trailing
zeros in the binary representation of
number I passed as an argument.
The binary number is represented
using 64 bits because the size of an
long number is 8 byte= 64 bits.
rotateLeft (long i, int d) It returns a long value by rotating
long number i passed as an
argument to left side by specific
position specified by d. As you
rotate the bits the bits that are
rotated from left side enters into
right side.
rotateRight (long i, int d) It returns a long value by rotating
long number i passed as an
argument to right side by specific
position specified by d. As you
rotate the bits the bits that are
rotated from right side enters into
left side.
2.8.5 Float Class:

19 | P a g e
This class wraps basic numeric data type float.
Constructor of Float Class:
 You can create an object of Float class using one of the following three
constructors:
(1) Float (float value)
(2) Float (double value)
(2) Float (String value)
Example:
Float F1 = new Float (10.2);
Float F2 = new Float (“12.2”);
Methods of Float Class:
 Following are the various methods of Float class:
Method Purpose
compareTo (float b) It compares the float value of invoking
Float object with the float value of b
passed as an argument. It returns an
integer value.
parseFloat (String S) It returns a float value of the number
contained in the string S.
compare (float f1, float f2) It compares two float values passed as
an argument and returns an integer
value.
2.8.6 Double Class:
This class wraps basic numeric data type double.
Constructor of Double Class:
 You can create an object of Double class using one of the following two
constructors:
(1) Double (double value)
(2) Double (String value)
Example:
Double D1 = Double Byte (12.23);
Double D2 = new Double (“12.43”);
Methods of Double Class:
 Following are the various methods of Double class:
Method Purpose
compareTo (double b) It compares the double value of
invoking Double object with the double

20 | P a g e
value of b passed as an argument. It
returns an integer value.
parseDouble (String S) It returns a double value of the number
contained in the string S.
compare (double d1, double It compares two double values passed
d2) as an argument and returns an integer
value.
2.8.7 Character Class:
This class wraps basic data type char.
Constructor of Character Class:
 You can create an object of Character class using following
constructor:
(1) Character (char value)
Example:
Character C1 = new Character (‘C’);
Methods of Character Class:
 Following are the various methods of Character class:
Method Purpose
char charValue () It returns the char value of invoking
Character object.
compareTo (char b) It compares the char value of invoking
Character object with the char value of
b passed as an argument. It returns an
integer value.
0 = equal
1 = Not equal
parseBoolean (String S) It returns a boolean value of the string
S. It returns true if string S contains
value true otherwise it returns false.
isDigit (char C) It returns a boolean value if passed
character C is digit otherwise it returns
false.
isLetter (char C) It returns a boolean value if passed
character C is letter otherwise it returns
false.
isLetterOrDigit (char C) It returns a boolean value if passed
character C is letter or digit otherwise it
returns false.

21 | P a g e
isLowerCase (char C) It returns a boolean value if passed
character C is in lower case letter
otherwise it returns false.
isUpperCase (char C) It returns a boolean value if passed
character C is in upper case letter
otherwise it returns false.
isSpace (char C) It returns a boolean value if passed
character C is space otherwise it
returns false.
toUpperCase (char C) It converts the passed character C in to
upper case letter and returns it.
toLowerCase (char C) It converts the passed character C in to
lower case letter and returns it.
2.8.8 Boolean Class:
This class wraps basic boolean data type.
Constructor of Boolean Class:
 You can create an object of Boolean class using one of the following
two constructor:
(1) Boolean (boolean value)
(2) Boolean (String value)
Example:
Boolean B1 = new Boolean (true);
Boolean B2 = new Boolean (“false”);
Instance variable of Boolean Class:
 Boolean class having three instance variable declared inside it. Which
are given below:
(1) TRUE: It is an object of Boolean class that is equivalent to the
primitive boolean value true.
(2) FALSE: It is an object of Boolean class that is equivalent to the
primitive boolean value false.
(3) TYPE: It returns the basic type of the value that is represented by
Boolean class. It is boolean.
Methods of Boolean Class:
 Following are the various methods of Boolean class:
Method Purpose
boolean booleanValue () It returns the boolean value of invoking
Boolean object.

22 | P a g e
compareTo (boolean b) It compares the boolean value of
invoking Boolean object with the
boolean value b passed as an
argument. It returns an integer value.
0 = equal
1 = Not equal
parseBoolean (String S) It returns a boolean value of the string
S. It returns true if string S contains
value true otherwise it returns false.

23 | P a g e

You might also like