Module 2 Half
Module 2 Half
Introducing Classes
Class Fundamentals
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. Because an object
is an instance of a class, you will o en see the two words object and instance used
interchangeably.
SYNTAX
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
type methodnameN(parameter-list) {
// body of method
Dept of CSE
HKBK College Of Engineering
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
Collec vely, the methods and variables defined within a class are called members of the class.
Variables defined within a class are called instance variables because each instance of the class
(that is, 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
class Box {
double width;
double height;
double depth;
For example, to assign the width variable of mybox the value 100, you would use the following
statement:
mybox.width = 100;
Dept of CSE
HKBK College Of Engineering
class Box {
double width;
double height;
double depth;
class BoxDemo {
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
Declaring Objects
When you create a class, you are crea ng a new data type.
However, obtaining objects of a class is a two-step process.
First, you 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.
Second, you must acquire an actual, physical copy of the object and assign it to that variable. You
can do this using the new operator.
The new operator dynamically allocates (that is, allocates at run me) memory for an object and
returns a reference to it.
This reference is, more or less, the address in memory of the object allocated by new. This
reference is then stored in the variable.
Thus, in Java, all class objects must be dynamically allocated.
Dept of CSE
HKBK College Of Engineering
This statement combines the two steps just described. It can be rewri en like this to show each
step more clearly:
Here, class-var is a variable of the class type being created. The classname is the name of the
class that is being instan ated.
The class name followed by parentheses specifies the constructor for the class.
A constructor defines what occurs when an object of a class is created.
Constructors are an important part of all classes and have many significant a ributes.
It is important to understand that new allocates memory for an object during run me.
The advantage of this approach is that your program can create as many or as few objects as it
needs during the execu on of your program.
However, since memory is finite, it is possible that new will not be able to allocate memory for
an object because insufficient memory exists.
If this happens, a run- me excep on will occur.
A class creates a new data type that can be used to create objects.
That is, a class creates a logical framework that defines the rela onship between its members.
When you declare an object of a class, you are crea ng an instance of that class.
Thus, a class is a logical construct. An object has physical reality.
Dept of CSE
HKBK College Of Engineering
Assigning Object Reference Variables
Object reference variables act differently when an assignment takes place.
Box b2 = b1;
A er this fragment executes, 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.
// ...
b1 = null;
Here, b1 has been set to null, but b2 s ll points to the original object.
Dept of CSE
HKBK College Of Engineering
Introducing 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 you create.
If the method does not return a value, its return type must be void.
The name of the method is specified by name. This can be any legal iden fier other than those
already used by other items within the current scope.
The parameter-list is a sequence of type and iden fier pairs separated by commas. Parameters
are essen ally variables that receive the value of the arguments passed to the method when it is
called.
If the method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling rou ne using the
following form of the return statement:
return value;
double width;
double height;
double depth;
void volume() {
System.out.print("Volume is ");
class BoxDemo3 {
Dept of CSE
HKBK College Of Engineering
Box mybox1 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox1.volume();
This program generates the following output, which is the same as the previous version.
Volume is 3000.0
Volume is 162.0
mybox1.volume();
Returning a Value
While the implementa on of volume( ) does move the computa on of a box’s volume
inside the Box class where it belongs, it is not the best way to do it.
class Box {
double width;
Dept of CSE
HKBK College Of Engineering
double height;
double depth;
double volume() {
class BoxDemo4 {
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
vol = mybox1.volume();
As you can see, when volume( ) is called, it is put on the right side of an assignment statement.
On the le is a variable, in this case vol, that will receive the value returned by volume( ).
Thus, a er vol = mybox1.volume(); executes, the value of mybox1.volume( ) is 3,000 and this
value then is stored in vol.
The type of data returned by a method must be compa ble with the return type specified by the
method. For example, if the return type of some method is boolean, you could not return an
integer.
The variable receiving the value returned by a method (such as vol, in this case) must also be
compa ble with the return type specified for the method.
Dept of CSE
HKBK College Of Engineering
That is, a parameterized method can operate on a variety of data and/or be used in a number of
slightly different situa ons
int square()
return 10 * 10;
While this method does, indeed, return the value of 10 squared, its use is very limited.
However, if you modify the method so that it takes a parameter, as shown next, then you 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. That is, square( ) is now a
general-purpose method that can compute the square of any integer value, rather than just 10.
Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
In the first call to square( ), the value 5 will be passed into parameter i.
In the second call, I will receive the value 9.
The third invoca on passes the value of y, which is 2 in this example.
As these examples show, square( ) is able to return the square of whatever data it is
passed
A parameter is a variable defined by a method that receives a value when the method is
called. For example, in square( ), i is a parameter.
An argument is a value that is passed to a method when it is Invoked.
For example, square(100) passes 100 as an argument. Inside square( ), the parameter i
receives that value.
Dept of CSE
HKBK College Of Engineering
Thus, a be er approach to se ng the dimensions of a box is to create a method that
takes the dimensions of a box in its parameters and sets each instance variable
appropriately.
This concept is implemented by the following program:
class Box {
double width;
double height;
double depth;
double volume() {
width = w;
height = h;
depth = d;
class BoxDemo5 {
double vol;
mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
Dept of CSE
HKBK College Of Engineering
// get volume of second box
vol = mybox2.volume();
}}
As you can see, the setDim( ) method is used to set the dimensions of each box. For example,
when mybox1.setDim(10, 20, 15); is executed, 10 is copied into parameter w, 20 is copied
into h, and 15 is copied into d.
Inside setDim( ) the values of w, h, and d are then assigned to width, height, and depth,
respec vely.
Constructors
It can be tedious to ini alize all of the variables in a class each me an instance is
created.
Even when you add convenience func ons like setDim( ), it would be simpler and more
concise to have all of the setup done at the me the object is first created.
Because the requirement for ini aliza on is so common, Java allows objects to ini alize
themselves when they are created.
This automa c ini aliza on is performed through the use of a constructor.
A constructor ini alizes an object immediately upon crea on.
It has the same name as the class in which it resides and is syntac cally similar to a
method.
Once defined, the constructor is automa cally called immediately a er the object is
created, before the new operator completes.
Constructors look a li le strange because they have no return type, not even void.
This is because the implicit return type of a class’ constructor is the class type itself.
It is the constructor’s job to ini alize the internal state of an object so that the code
crea ng an instance will have a fully ini alized, usable object immediately.
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Construc ng Box");
width = 10;
Dept of CSE
HKBK College Of Engineering
height = 10;
depth = 10;
double volume() {
class BoxDemo6 {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
Construc ng Box
Construc ng Box
Volume is 1000.0
Volume is 1000.0
Now you can understand why the parentheses are needed a er the class name. What is
actually happening is that the constructor for the class is being called. Thus, in the line
Box mybox1 = new Box();
Dept of CSE
HKBK College Of Engineering
new Box( ) is calling the Box( ) constructor new .
When you do not explicitly define a constructor for a class, then Java creates a default
constructor for the class
Parameterized Constructors
While the Box( ) constructor in the preceding example does ini alize a Box object, it is not very
useful—all boxes have the same dimensions.
What is needed is a way to construct Box objects of various dimensions.
The easy solu on is to add parameters to the constructor
class Box {
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
double volume() {
class BoxDemo7 {
Dept of CSE
HKBK College Of Engineering
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
Volume is 3000.0
Volume is 162.0
this.width = w;
this.height = h;
this.depth = d;
Uses of this:
Dept of CSE
HKBK College Of Engineering
this.width = width;
this.height = height;
this.depth = depth;
NOTE: The use of this in such a context can some mes be confusing, and some
programmers are careful not to use local variables and formal parameter names that hide
instance variables.
Garbage Collec on
Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
realloca on.
Java takes a different approach; it handles dealloca on for you automa cally.
The technique that accomplishes this is called garbage collec on.
It works like this: 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.
There is no explicit need to destroy objects as in C++.
Garbage collec on only occurs sporadically (if at all) during the execu on of your
program.
It will not occur simply because one or more objects exist that are no longer used.
Dept of CSE
HKBK College Of Engineering