Module - 2
Module - 2
Module - 2
Syllabus
Introducing Classes: Class Fundamentals, Declaring Objects, Assigning Object Reference Variables,
Introducing Methods, Constructors, The this Keyword, Garbage Collection.
Methods and Classes: Overloading Methods, Objects as Parameters, Argument Passing, Returning
Objects, Recursion, Access Control, Understanding static, Introducing final, Introducing Nested and
Inner Classes.
Class is a basis of OOP languages. It is a logical construct which defines shape and nature of an
object. Entire Java is built upon classes.
Class Fundamentals
Class can be thought of as a user-defined data type. We can create variables (objects) of that data
type. So, we can say that class is a template for an object and an object is an instance of a class.
Most of the times, the terms object and instance are used interchangeably.
The General Form of a Class
A class contains data (member or instance variables) and the code (member methods) that
operate on the data. The general form can be given as –
class classname
{
type var1;
type var2;
…….
type method1(para_list)
{
//body of method1
}
type method2(para_list)
{
//body of method2
}
………..
}
Here, classname is any valid name given to the class. Variables declared within a class are called
as instance variables because every instance (or object) of a class contains its own copy of these
variables. The code is contained within methods. Methods and instance variables collectively
called as members of the class.
1|Page
Object Oriented Programming with JAVA 2023
A Simple Class: Here we will consider a simple example for creation of class, creating objects
and using members of the class. One can store the following program in a single file called
BoxDemo.java. (Or, two classes can be saved in two different files with the names Box.java and
BoxDemo.java.)
class Box {
double w, h, d;
}
class BoxDemo{
public static void main(String args[]) {
Box b1=new Box();
Box b2=new Box();
double vol;
b1.w=2;
b1.h=4;
b1.d=3;
b2.w=5;
b2.h=6;
b2.d=2;
vol=b1.w*b1.h*b1.d;
System.out.println("Volume of Box1 is " + vol);
vol=b2.w*b2.h*b2.d;
System.out.println("Volume of Box2 is " + vol);
}
}
The above program is compiled two class files will be created by the name Box.class and
BoxDemo.class.
In the above example, we have created a class Box which contains 3 instance variables w, h, d.
Box b1=new Box(); This
statement creates a physical
memory for one object of
Box class. Every object is
an instance of a class, and
so, b1 and b2 will have their
own copies of instance
variables w, h and d. The
memory layout for one object allocation can be shown as in the above figure.
2|Page
Object Oriented Programming with JAVA 2023
Declaring Objects: Creating a class means having a user-defined data type. To have a variable of this
new data type, we should create an object. Consider the following declaration:
Box b1;
This statement will not actually create any physical object, but the object name b1 can just refer to the
actual object on the heap after memory allocation as follows:
b1 = new Box ();
We can even declare an object and allocate memory using a single statement.
Box b1=new Box();
Without the usage of new, the object contains null. Once memory is allocated dynamically, the object b1
contains the address of real object created on the heap. The memory map is as shown in the following
diagram.
3|Page
Object Oriented Programming with JAVA 2023
4|Page
Object Oriented Programming with JAVA 2023
body of method is a code segment written to carry out some process for which the method is
meant for.
return is a keyword used to send value to the calling method. This line will be absent if the
ret_type is void.
Adding Methods to Box class: Though it is possible to have classes with only instance
variables, it is advisable to have methods to operate on those data. Because, methods acts as
interface to the classes. This allows the class implementer to hide the specific layout of internal
data structures behind cleaner method abstractions. In addition to defining methods that provide
access to data, you can also define methods that are used internally by the class itself. Consider
the following example :
class Box
{
double w, h, d;
void volume()
{
System.out.println("The volume is " + w*h*d);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box b1=new Box();
Box b2=new Box();
b1.w=2;
b1.h=4;
b1.d=3;
b2.w=5;
b2.h=6;
b2.d=2;
b1.volume();
b2.volume();
}
}
In the above program, the Box objects b1 and b2 are invoking the member method volume() of
the Box class to display the volume. To attach an object name and a method name, we use dot (.)
operator. Once the program control enters the method volume(), we need not refer to object
5|Page
Object Oriented Programming with JAVA 2023
6|Page
Object Oriented Programming with JAVA 2023
7|Page
Object Oriented Programming with JAVA 2023
double volume()
{
return w*h*d;
}
Box() //ordinary constructor
{
w=h=d=5;
}
Box(double wd, double ht, double dp) //parameterized constructor
{
w=wd;
h=ht;
d=dp;
}
}
class BoxDemo
{
public static void main(String args[]) {
Box b1=new Box();
Box b2=new Box();
Box b3=new Box(2,4,3);
System.out.println("The volumeof b1 is " + b1.volume());
System.out.println("The volumeof b2 is " + b2.volume());
System.out.println("The volumeof b3 is " + b3.volume());
}
}
When we create two objects b1 and b2, the constructor with no arguments will be called and the
all the instance variables w, h and d are set to 5. Hence volume of b1 and b2 will be same (that is
125 in this example). But, when we create the object b3, the parameterized constructor will be
called and hence volume will be 24.
Points about constructor
• Every class is provided with a default constructor which initializes all the data
members to respective default values. (Default for numeric types is zero, for
character and strings it is null and default value for Boolean type is false.)
• In the statement
classname ob= new classname(); //the term classname() is actually a constructor call.
• If the programmer does not provide any constructor of his own, then the above statement
will call default constructor.
8|Page
Object Oriented Programming with JAVA 2023
• If the programmer defines any constructor, then default constructor of Java can not be
used.
• So, if the programmer defines any parameterized constructor and later would like to
create an object without explicit initialization, he has to provide the default constructor
by his own.
• For example, the above program, if we remove ordinary constructor, the statements like
Box b1=new Box();// will generate error. To avoid the error, we should write a default
constructor like Box(){ }
Now, all the data members will be set to their respective default values.
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. this keyword can be used inside any method to refer to the current object. That
is, this is always a reference to the object which invokes the method call. For example volume()
can be written as :
double volume()
{
return this.w * this.h * this.d;
}
Here, usage of this is not mandatory as it is implicit. But, in some of the situations, it is useful.
Instance Variable Hiding
As we know, in Java, we cannot have two local variables with the same name inside the same or
enclosing scopes. But we can have local variables, including formal parameters to methods,
which overlap with the names of the class’ instance variables. However, when a local variable
has the same name as an instance variable, the local variable hides the instance variable. The
following code extract for a constructor in the above constructor example, we will not get an
expected output.
Box(double w, double h, double d)
{
w=w;
h=h;
d=d;
}
Here note that, formal parameter names and data member names match exactly. To avoid the
problem, it can be written as
9|Page
Object Oriented Programming with JAVA 2023
A Stack Class
To summarize the concepts of encapsulation, class, constructor, member initialization etc, we
will now consider a program to implement stack operations.
Concept of Stack: A stack is a Last in First Out (LIFO) data structure. Following figure depicts
the basic operations on stack:
Inserting an element into a stack is known as push operation, whereas deleting an element from
the stack is pop operation. An attempt made to push an element into a full stack is stack
overflow and an attempt to delete from empty stack is stack underflow.
class Stack
{
int st[] = new int[5];
int top;
Stack()
{
top = -1;
}
void push(int item)
{
if(top==4)
System.out.println("Stack is full.");
else
st[++top] = item;
}
int pop()
{
11 | P a g e
Object Oriented Programming with JAVA 2023
if(top==-1)
{
System.out.println("Stack underflow.");
return 0;
}
else
return st[top--];
}
}
class StackDemo {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
for(int i=0; i<5; i++)
mystack1.push(i);
for(int i=5; i<10; i++)
mystack2.push(i);
System.out.println("Contents of mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Contents of mystack2:");
for(int i=0; i<5; i++)
System.out.println(mystack2.pop());
}
}
Overloading Methods
Having more than one method with a same name is called as method overloading. To implement
this concept, the constraints are:
• The number of arguments should be different, and/or
• Type of the arguments must be different.
• Only the return type of the method is not sufficient for overloading.
class Overload
{
void test() //method without any arguments
{
System.out.println("No parameters");
}
void test(int a) //method with one integer argument
{
12 | P a g e
Object Oriented Programming with JAVA 2023
13 | P a g e
Object Oriented Programming with JAVA 2023
}
class OverloadConstructDemo {
public static void main(String args[])
{
OverloadConstruct ob1= new OverloadConstruct();
OverloadConstruct ob2= new OverloadConstruct(10);
OverloadConstruct ob3= new OverloadConstruct(5,12);
}
}
Using Objects as Parameters
Just similar to primitive types, even object of a class can also be passed as a parameter to any
method.
Consider the example given below
class Test {
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
boolean equals(Test ob)
{
if(ob.a == this.a && ob.b == this.b)
return true;
else
return false;
}
}
class PassOb{
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Using one object to initialize the other: Sometimes, we may need to have a replica of one
object. The usage of following statements will not serve the purpose.
Box b1=new Box(2,3,4);
14 | P a g e
Object Oriented Programming with JAVA 2023
Box b2=b1;
In the above case, both b1 and b2 will be referring to same object, but not two different objects.
So, we can write a constructor having a parameter of same class type to clone an object.
class Box {
double h, w, d;
Box(double ht, double wd, double dp)
{
h=ht; w=wd; d=dp;
}
Box (Box bx) //observe this constructor
{
h=bx.h; w=bx.w; d=bx.d;
}
void vol()
{
System.out.println("Volume is " + h*w*d);
}
public static void main(String args[]) {
Box b1=new Box(2,3,4);
Box b2=new Box(b1); //initialize b2 using b1
b1.vol();
b2.vol();
}
}
A Closer Look at Argument Passing
In Java, there are two ways of passing arguments to a method.
Call by value: This approach copies the value of an argument into the formal parameter of the
method. Therefore, changes made to the parameter of the method have no effect on the
argument.
Call by reference: In this approach, a reference to an argument is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified in the call.
This means that changes made to the parameter will affect the argument used to call the
subroutine.
In Java, when we pass a primitive type to a method, it is passed by value. When we pass an
object to a method, they are passed by reference. While we create a variable of a class type, we
are creating only a reference to an object. Thus, when we pass this reference to a method, the
parameter that receives it will refer to the same object as that referred to by the argument.
15 | P a g e
Object Oriented Programming with JAVA 2023
This effectively means that objects are passed to methods by use of call-by-reference. Changes
to the object inside the method do affect the object used as an argument.
class Test {
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("after call: " + ob.a + " " + ob.b);
}
}
Returning Objects: In Java, a method can return an object of user defined class.
class Test {
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
16 | P a g e
Object Oriented Programming with JAVA 2023
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " + ob2.a);
}
}
Recursion: A method which invokes itself either directly or indirectly is called as recursive
method. Every recursive method should satisfy following constraints:
• It should have at least one non-recursive terminating condition.
• In every step, it should be nearer to the solution (that is, problem size must be decreasing)
class Factorial {
int fact(int n)
{
if (n==0)
return 1;
return n*fact(n-1);
}
}
class FactDemo {
public static void main(String args[]) {
Factorial f= new Factorial();
System.out.println("Factorial 3 is "+ f.fact(3));
System.out.println("Factorial 8 is "+ f.fact(8));
}
}
Introducing Access Control
Encapsulation feature of Java provides a safety measure viz. access control. Using access
specifiers, we can restrict the member variables of a class from outside manipulation. Java
provides following access specifiers:
• public
• private
• protected
Along with above access specifiers, Java defines a default access level. Some aspects of access
control are related to inheritance and package (a collection of related classes).
• The protected specifier is applied only when inheritance is involved.
17 | P a g e
Object Oriented Programming with JAVA 2023
• When a member of a class is modified by the public specifier, then that member can be
accessed by any other code.
• When a member of a class is specified as private, then that member can only be accessed
by other members of its class. When no access specifier is used, then by default the
member of a class is public within its own package, but cannot be accessed outside of its
package.
Example
public int x;
private char ch;
Consider a program given below –
class Test {
int a;
public int b;
private int c;
void setc(int i)
{
c = i;
}
int getc()
{
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 10;
ob.b = 20;
// ob.c = 100; // inclusion of this line is Error!
ob.setc(100);
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " "
+ ob.getc());
}
}
Understanding static
When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object. Instance variables declared as static are global variables.
When objects of its class are declared, no copy of a static variable is made. Instead, all instances
18 | P a g e
Object Oriented Programming with JAVA 2023
19 | P a g e
Object Oriented Programming with JAVA 2023
Introducing final
A variable can be declared as final. Doing so prevents its contents from being modified. This
means that we must initialize a final variable when it is declared. For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Subsequent parts of the program can now use FILE_OPEN, etc., as if they were constants,
without fear that a value has been changed.
• In addition to fields, both method parameters and local variables can be declared final.
• Declaring a parameter final prevents it from being changed within the method.
• Declaring a local variable final prevents it from being assigned a value more than once.
• The keyword final can also be applied to methods, but its meaning is substantially
different than when it is applied to variables.
Arrays Revisited
Arrays have been discussed earlier. An important point to be noted with arrays is: arrays are
implemented as objects in Java. Because of this, we can use a special instance variable length to
know the size of an array.
class Test {
public static void main(String args[]) {
int a1[]=new int[10];
int a2[]={1, 2, 3, 4, 5};
int a3[]={3, 8, -2, 45, 9, 0, 23};
System.out.println(“Length of a1 is” + a1.length);
System.out.println(“Length of a2 is” + a2.length);
System.out.println(“Length of a3 is” + a3.length);
}
}
Introducing Nested and Inner Classes
It is possible to define a class within another class and such classes are known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is
defined within class A, then B does not exist independently of A. A nested class has access to
the members, including private members, of the class in which it is nested. But, the enclosing
class does not have access to the members of the nested class. A nested class that is declared
20 | P a g e
Object Oriented Programming with JAVA 2023
directly within its enclosing class scope is a member of its enclosing class. It is also possible to
declare a nested class that is local to a block.
There are two types of nested classes: static and non-static. A static nested class is has the
static modifier applied and it must access the non-static members of its enclosing class through
an object. It cannot refer to non-static members of its enclosing class directly. Because of this
restriction, static nested classes are seldom used.
An inner class is a non-static nested class. It has access to all of the variables and methods of its
outer class and may refer to them directly in the same way that other non-static members of the
outer class do.
Consider the example: class named Outer has one instance variable named outer_x, one
instance method named test( ), and defines one inner class called Inner.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display(); }
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x); }
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
21 | P a g e
Object Oriented Programming with JAVA 2023
Question Bank:
1. Define class. Give syntax and example.
2. Briefly explain static members of the class with suitable examples.
3. Discuss method overloading. Write a program to overload a method area() to compute
area of a triangle and a circle.
4. Define a constructor. What are the salient features of Constructor? Write a Java program
to show these features.
5. How do you overload a constructor? Explain with a program.
6. Define recursion. Write a recursive program to find nth Fibonacci number.
7. Write a program to implement stack operations.
8. What are different parameter passing techniques in Java? Discuss the salient features of
the same.
9. What are various access specifiers in Java? List out the behavior of each of them.
10. Create a Java class called Student with the following details as variables (USN, Name,
Branch, Phone Number). Write a Java program to create n student objects and print
USN, Name, Branch, and Phone number with suitable heading.
11. Discuss usage of final keyword in Java. Give suitable examples.
12. Write a note on:
a. Use of this keyword
b. Garbage Collection in Java
c. Finalize() method
13. What is inner class demonstrate with an example.
22 | P a g e