OOPS WITH JAVA – BCS306A Module 2
Module 2
Chapter 1
Introducing Classes
• Class defines the shape and nature of an object.
• Class forms the basis for object-oriented programming in Java.
• Any concept can be implemented in a Java program must be encapsulated within a class.
Class Fundamentals
• A class defines a new data type. Once defined, this new type can be used to create objects of that type.
• Thus, a class is a template for an object, and an object is an instance of a class.
The General Form of a Class
• Class specifies the data that it contains and the code that operates on that data.
• While very simple classes may contain only code or only data, most real-world classes contain both.
• A class is declared by use of the class keyword.
A simplified general form of a class definition is shown here:
class classname
{ type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
//body of method
}
type methodname2(parameter-list)
{
//body of method
}
//…. type methodnameN(parameter-
list)
{
//body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is contained within
methods.
Collectively, the methods and variables defined within a class are called members of the class.
Thus the methods that determine how a class’ data can be used. each object of the class contains its own copy
of these variables.
Thus, the data for one object is separate and unique from the data for another.
A Simple Class
Here is a class called Box that defines three instance variables: width, height, and depth.
Dept of AI & ML, CBIT Kolar 1
OOPS WITH JAVA – BCS306A Module 2
class Box
{ double width;
double height;
double depth;
}
class BoxDemo2
{ public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol; [Link]
= 10; [Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
// compute volume of first box
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
// compute volume of second box
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol); }
}
output: Volume is 3000.0 Volume is 162.0 mybox1’s data is completely
separate from the data contained in mybox2.
3.1 Declaring Objects
When a class is created , we are creating a new data type. We can use this type to declare objects of that
[Link], obtaining objects of a class is a two-step process.
1. First, we must declare a variable of the class type. This variable does not define an object. Instead,
it is simply a variable that can refer to an object.
2. Second, we must acquire an actual, physical copy of the object and assign it to that variable by
using the new operator.
The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a
reference to it
Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like this to show each step more
clearly:
Box mybox; // declare reference to object mybox
= new Box(); // allocate a Box object
Dept of AI & ML, CBIT Kolar 2
OOPS WITH JAVA – BCS306A Module 2
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply
makes b2 refer to the same object as does b1.
Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they
are the same object.
Although b1 and b2 both refer to the same object, they are not linked in any other way.
For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
Introducing Methods
classes usually consist of two things: instance variables and methods. This is the general form of a
method: type name(parameter-list)
{
//body of method
}
Here, type specifies the type of data returned by the method. This can be any valid type, including
class types that we create.
If the method does not return a value, its return type must be void. The name of the method is specified by
name.
. The parameter-list is a sequence of type and identifier pairs separated by commas.
class Box
{ double width;
double height;
double depth;
//
void volume()
{
[Link]("Volume is ");
[Link](width * height * depth);
}
}
class BoxDemo3
{ public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
Dept of AI & ML, CBIT Kolar 3
OOPS WITH JAVA – BCS306A Module 2
[Link] = 3;
[Link] = 6;
[Link] = 9;
// display volume of first box
[Link]();
// display volume of second box
[Link]();
}
}
This program generates the following output, which is the same as the previous version. Volume is
3000.0
Volume is 162.0
Returning a Value
Java has return keyword.
Java return keyword is used to complete the execution of a [Link]
return followed by the appropriate value that is returned to the [Link] value
depends on the method return type like int method always return an integer
value.
class Box
{ double width;
double height;
double depth;
//compute and return volume
double volume()
{ return width * height * depth; }
}
class BoxDemo4
{ public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol; [Link]
= 10; [Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
// get volume of first box
vol = [Link]();
[Link]("Volume is " + vol);
Dept of AI & ML, CBIT Kolar 4
OOPS WITH JAVA – BCS306A Module 2
//get volume of second box
vol = [Link]();
[Link]("Volume is " + vol);
}
}
Adding a Method That Takes Parameters
Parameters allow a method to be generalized.
That is, a parameterized method can operate on a variety of data and/or be used in a number of slightly
different situations.
Here is a method that returns the square of the number 10:
int square()
{ return 10 * 10; }
While this method does, indeed, return the value of 10 squared, its use is very limited. However, if
we modify the method so that it takes a parameter, as shown next, then we can make square( ) much
more useful.
int square(int i)
{ return i * i;
}
Now, square( ) will return the square of whatever value it is called
with. // This program uses a parameterized method.
class Box
{ double width;
double height;
double depth;
double volume()
{ return width * height * depth;
}
void setDim(double w, double h, double d)
{ width = w;
height = h;
depth = d;
}
}
class BoxDemo5
{ public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
[Link](10, 20, 15);
[Link](3, 6, 9); //
get volume of first box vol
= [Link]();
[Link]("Volume is " + vol);
//get volume of second box
vol = [Link]();
Dept of AI & ML, CBIT Kolar 5
OOPS WITH JAVA – BCS306A Module 2
[Link]("Volume is " + vol);
}
}
Constructors
It can be tedious to initialize all of the variables in a class each time an instance is created.
Thus, automatic initialization is performed with a constructor. A constructor initializes an object
immediately upon creation.
It has the same name as the class in which it resides and is syntactically similar to a method.
The constructor is automatically called immediately after the object is created, before the new
operator completes.
Constructors have no return type, not even void. This is because the implicit return type of a class’
constructor is the class type itself.
class Box
{ double width;
double height;
double depth;
Box()
{
[Link]("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume()
{ return width * height * depth; }
}
class BoxDemo6
{ public static void main(String args[])
{
Box mybox1 = new Box(); Box
mybox2 = new Box(); double
vol;
//get volume of first box vol
= [Link]();
[Link]("Volume is " + vol);
//get volume of second box
vol = [Link]();
[Link]("Volume is " +
vol); }
}
Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Dept of AI & ML, CBIT Kolar 6
OOPS WITH JAVA – BCS306A Module 2
Both mybox1 and mybox2 were initialized by the Box ( ) constructor when they were created. Since
the constructor gives all boxes the same dimensions, 10 by 10 by 10, both mybox1 and mybox2 will
have the same volume
Parameterized Constructors
While the Box ( ) constructor in the preceding example initializes with value [Link] boxes have the same
dimensions.
Box objects of various dimensions can be assigned by using parameterized constructor.
class Box
{ double width;
double height;
double depth;
Box(double w, double h, double d)
{ width = w;
height = h;
depth = d;
}
double volume()
{ return width * height * depth; }
}
class BoxDemo7
{ public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
//get volume of first box
vol = [Link]();
[Link]("Volume is " + vol);
//get volume of second box
vol = [Link]();
[Link]("Volume is " + vol);
}
}
output : Volume
is 3000.0
Volume is 162.0
The this Keyword
this can be used inside any method to refer to the current object.
That is, this is always a reference to the object on which the method was invoked.
// A redundant use of this.
Box(double w, double h, double d)
Dept of AI & ML, CBIT Kolar 7
OOPS WITH JAVA – BCS306A Module 2
{ [Link] = w;
[Link] = h;
[Link] = d;
}
Instance Variable Hiding
It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes.
However, when a local variable has the same name as an instance variable, the local variable hides the
instance variable.
//Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{ [Link] = width;
[Link] = height;
[Link] = depth; }
Garbage Collection
Since objects are dynamically allocated by using the new operator, how such objects are
destroyed and their memory released for later reallocation.
In some languages, such as C++, dynamically allocated objects must be manually released by use of a
delete operator.
Java handles deallocation automatically. The technique that accomplishes this is called garbage
collection.
When no references to an object exist, that object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
Garbage collection only occurs sporadically (if at all) during the execution of program.
The finalize ( ) Method
An object will need to perform some action when it is destroyed.
If an object is holding some non-Java resource such as a file handle or character font, then we might
want to make sure these resources are freed before an object is destroyed. To handle such situations,
Java provides a mechanism called finalization.
Finalize( ) is called by the garbage collector on an object when garbage collection determines that
there is no more references to the object.
To add a finalizer to a class, simply define the finalize ( ) method.
The Java run time calls that method whenever it is about to recycle an object of that class.
Inside the finalize ( ) method, you will specify those actions that must be performed before an object
is destroyed.
The finalize ( ) method has this general form:
protected void finalize( )
{
Dept of AI & ML, CBIT Kolar 8
OOPS WITH JAVA – BCS306A Module 2
//finalization code
here }
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside
its class.
finalize( ) is only called just prior to garbage collection. It is not called when an object goes out-of-
scope.
Dept of AI & ML, CBIT Kolar 9