OOP - Module 2 - Notes
OOP - Module 2 - Notes
III Semester
` Page 1
MODULE 2: Classes, Methods & Classes OOP- BCS306A
Module 2
Methods and Classes: Overloading Methods, Objects as Parameters, Argument Passing, Returning
Objects, Access Control, Understanding static, Introducing final, Introducing Nested and Inner
Classes.
Chapter 6, 7
` Page 2
MODULE 2: Classes, Methods & Classes OOP- BCS306A
1. CLASS FUNDAMENTALS
The class is at the core of Java. It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.
A class is declared by using class keyword. class is a template for an object, and an object is
an instance of a class.
Syntax:
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. 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
• A class called Box that defines three instance variables: width, height, and depth. a class defines a
new type of data. In this case, the new data type is called Box. To actually create a Box object, you
will use the following statement:
Box mybox = new Box( ); // create a Box object called mybox
• After this statement executes, mybox will be an instance of Box. Thus, it will have “physical”
reality. The file that contains this program [Link], because the main( ) method is in the
class called BoxDemo, not the class called Box. mybox1’s data is completely separate from the data
contained in mybox2.
` Page 3
MODULE 2: Classes, Methods & Classes OOP- BCS306A
[Link] = 10;
[Link] = 20;
[Link] = 15;
Output:
Volume is 3000.0
Each object has its own copies of the instance variables. This means that if 2 Box objects are there,
each has its own copy of depth, width and height. The changes to the instance variables of one object
have no effect on the instance variables of another. The following program declares two Box
objects:
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
` Page 4
MODULE 2: Classes, Methods & Classes OOP- BCS306A
}
}
Output:
Volume is 3000.0
Volume is 162.0
First, you must declare a variable of the class type which 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 using the new operator. The new operator dynamically allocates memory for
an object and returns a reference to it where the address is stored.
OR
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
` Page 5
MODULE 2: Classes, Methods & Classes OOP- BCS306A
Object:
o Object is a real world entity.
o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class.
` Page 6
MODULE 2: Classes, Methods & Classes OOP – BCS306A
• Although b1 and b2 both refer to the same object, they are not linked in any other way.
• For example, a subsequent assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2.
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
type name(parameter-list) {
// body of method
return value;
}
Methods define the interface to most classes. This allows the class implementer to hide the
specific layout of internal data structures behind cleaner method abstractions. Defining
7
MODULE 2: Classes, Methods & Classes OOP – BCS306A
methods provide access to data, you can also define methods that are used internally by the
class itself.
Class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
class Demo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = [Link]();
[Link](―Volume is ― + vol);
vol = [Link]();
[Link](―Volume is ― + vol);
}
}
• Use methods to access the instance variables defined by the class. In fact, methods define the
interface to most classes. This allows the class implementor 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.
Let’s begin by adding a method to the Box class. since the volume of a box is dependent upon the
size of the box, it makes sense to have the Box class compute it.
8
MODULE 2: Classes, Methods & Classes OOP – BCS306A
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;
[Link] = 3;
[Link] = 6;
[Link] = 9;
}
}
Output:
Volume is 3000.0
Volume is 162.0
• When [Link]( ) is executed, the Java run-time system transfers control to the code
defined inside volume( ).
• After the statements inside volume( ) have executed, control is returned to the calling routine,
and execution resumes with the line of code following the call.
• There is something very important to notice inside the volume( ) method: the instance variables
width, height, and depth are referred to directly, without preceding them with an object
name or the dot operator.
• When a method uses an instance variable that is defined by its class, it does so directly, without
explicit reference to an object and without use of the dot operator.
• A method can directly invoke all the instance variable of the class if the method is present in the
same class.
9
MODULE 2: Classes, Methods & Classes OOP – BCS306A
• This means that width, height, and depth inside volume( ) implicitly refer to the copies of
those variables found in the object that invokes volume( ).
Returning a Value
• While the implementation of volume( ) does move the computation of a box’s volume inside
the Box class where it belongs, it is not the best way to do it.
• A better way to implement volume( ) is to have it compute the volume of the box and return
the result to the caller.
Class Box {
double width;
double height;
double depth;
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;
vol = [Link]();
[Link](―Volume is ― + vol);
vol = [Link]();
[Link](―Volume is ― + vol);
}
}
When volume( ) is called, it is put on the right side of an assignment statement. On the left is a
variable, in this case vol, that will receive the value returned by volume( ). Thus, after
vol = [Link]();
executes, the value of [Link]( ) is 3,000 and this value then is stored in vol.
10
MODULE 2: Classes, Methods & Classes OOP – BCS306A
• While some methods don’t need parameters, most do. 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.
• Method Without Parameter Method with Parameter
int square( ) int square(int i)
{ {
return 10 * 10; return i*i;
} }
While this method does, indeed, return the value of 10 squared, its use is very limited. 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
• It is important to keep the two terms parameter and argument straight. 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.
• You can use a parameterized method to improve the Box class. In the preceding examples, the
dimensions of each box had to be set separately by use of a sequence of statements, such as:
[Link] = 10;
[Link] = 20;
[Link] = 15;
A better approach to setting 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.
11
MODULE 2: Classes, Methods & Classes OOP – BCS306A
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;
vol = [Link]();
[Link](―Volume is ― + vol);
vol = [Link]();
[Link](―Volume is ― + vol);
}
}
The setDim( ) method is used to set the dimensions of each box. For example, when
[Link](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, respectively.
2. CONSTRUCTORS
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.A constructor doesn’t have a return
[Link] name of the constructor must be the same as the name of the [Link] methods,
constructors are not considered members of a class.
12
MODULE 2: Classes, Methods & Classes OOP – BCS306A
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 demo
{
public static void main(String args[]) {
Box mybox1 = new Box();
double vol;
vol = [Link]();
[Link](―Volume is ― + vol);
}
}
13
MODULE 2: Classes, Classes & Methods OOP – BCS306A
Parameterized constructor
Class Student
{
int id;
String name;
Student(int I,String n)
{
id = I;
name = n;
}
void display()
{
[Link](id+‖ ―+name);
}
}
Class test{
public static void main(String args[])
{
Student s1 = new Student(111,‖Karan‖);
Student s2 = new Student(222,‖Aryan‖);
[Link]();
[Link]();
}
}
14
MODULE 2: Classes, Classes & Methods OOP – BCS306A
Objects as Parameters
Using Objects as Parameters: So far, we have only been using simple types as parameters to
methods. However, it is both correct and common to pass objects to methods. For example,
consider the following short program
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking
object boolean equalTo(Test o) {
if(o.a == a && o.b == 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); [Link]("ob1 == ob2: " +
[Link](ob2)); [Link]("ob1 == ob3: " +
[Link](ob3));
}
}
Exercise 1:
Write a java program to create 2 objects of complex numbers and pass these objects as
parameters to the methods. Perform addition of 2 complex numbers and return the sum as
an object.
Interestingly, you 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.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](rollno+" "+name+" "+fee);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}
}
Overloaded Constructors
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter [Link] compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
class Student{
int id;
String name;
int age;
Student (int i,String n)
{
id = i;
name = n;
}
Student (int i,String n,int a)
MODULE 2: Classes, Classes & Methods OOP – BCS306A
{
id = i;
name = n;
age=a;
}
void display()
{
[Link](id+" "+name+" "+age);
}
3. GARBAGE COLLECTION
In some languages, such as C++, dynamically allocated objects must be manually released by
use of a delete operator. Java takes a different approach; it handles deallocation for you
automatically. The technique that accomplishes this is called garbage collection. 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.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
4. A Stack Class
class Stack
{
int stck[] = new int[10];
int top;
// Initialize top-of-
stack Stack()
{
top = -1;
MODULE 2: Classes, Classes & Methods OOP – BCS306A
int pop()
{
if(top < 0) {
[Link]("Stack underflow.");
return 0;
}
else
return stck[top--];
}
}
class TestStack
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
[Link]("Stack in mystack1:");
for(int i=0; i<10; i++)
[Link]([Link]());
[Link]("Stack in mystack2:");
for(int i=0; i<10; i++)
[Link]([Link]());
}
}
Stack in mystack1:
9
8
7
6
5
4
MODULE 2: Classes, Methods & Classes OOP- BCS306A
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
10
1. Overloading Methods
In Java, it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different. Method overloading is
also known as Static Polymorphism.
Argument lists could differ in –
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.
When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call. Thus,
overloaded methods must differ in the type and/or number of their parameters. While
overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.
MODULE 2: Classes, Methods & Classes OOP- BCS306A
class Calculate
{
void sum (int a, int b)
{
[Link]("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
[Link]("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
[Link] (8,5); //sum(int a, int b) is method is called.
class Overloading3
{
public void disp(char c, int num)
{
[Link]("c ");
[Link]("num ");
}
public void disp(int num, char c)
{
[Link]("c ");
[Link]("num ");
}
}
class Sample3
{
public static void main(String args[])
{
Overloading3 obj = new Overloading3();
[Link]('x', 51 );
[Link](52, 'y');
}
}
MODULE 2: Classes, Methods & Classes OOP- BCS306A
Output:
ob1 == ob2: true
ob1 == ob3: false
• The equals( ) method inside Test compares two objects for equality and returns the result. That is,
it compares the invoking object with the one that it is passed.
• If they contain the same values, then the method returns true. Otherwise, it returns false. Notice
that the parameter o in equals( ) specifies Test as its type.
3. Argument Passing
Two ways that a computer language can pass an argument to a subroutine.
a. Call-by-value:
It copies the argument into the formal parameter of the subroutine. The changes made to the parameter
of the subroutine have no effect on the argument.
class Test
{
MODULE 2: Classes, Methods & Classes OOP- BCS306A
b. Call-by-reference:
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.
class Test
{
int a,b;
Test(int i, int j)
{
a=i;
b=j;
}
//pass an object
void meth(Test o)
{
o.a*=2;
o.b/=2;
}
}
class PassObjRef
MODULE 2: Classes, Methods & Classes OOP- BCS306A
{
public static void main(String[] args)
{
Test ob=new Test(15, 20);
[Link](“ob.a and ob.b before call: “ +a+ “ “ +b);
[Link](ob);
[Link](“ob.a and ob.b after call: “ +a+ “ “ +b);
}
}
Output:
Ob.a and ob.b before call: 15 20
Ob.a and ob.b after call: 30 10
The actions inside meth() have affected the object used as an argument.
4. Returning Objects
A method can return any type of data, including class types that you create. The incrByTen() method
returns an object in which the value of a is ten greater than it is in the invoking object.
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);
Test ob2;
Ob2=[Link]();
[Link](“ob1.a: “ +ob1.a);
[Link](“ob2.a: “ +ob2.a);
Ob2=[Link]();
MODULE 2: Classes, Methods & Classes OOP- BCS306A
Output:
Ob1.a: 2
Ob2.a: 12
Ob2.a after second increase: 22
Each time incrByTen() is invoked, a new object is created, and a reference to it is returned to the
calling routine.
5. Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself. As
it relates to Java programming, recursion is the attribute that allows a method to call itself. A
method that calls itself is said to be recursive.
class Factorial {
int fact(int n) {
int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
Advantages of Recursion
1. Reduces time complexity.
2. Performs better in solving problems based on tree structures.
MODULE 2: Classes, Methods & Classes OOP- BCS306A
6. Access Control
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
public:
A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class
belonging to the Java Universe. It has the widest scope among all other modifiers.
//save by [Link]
package pack;
public class A
{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
private:
Methods, Variables and Constructors that are declared private can only be accessed within the
declared class itself. Private access modifier is the most restrictive access level. Class and
interfaces cannot be private. Variables that are declared private can be accessed outside the
class if public getter methods are present in the class.
MODULE 2: Classes, Methods & Classes OOP- BCS306A
class A
{
private int data=40;
private void msg()
{
[Link]("Hello java");}
}
protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed
only by the subclasses in other package or any class within the package of the protected members'
class. The protected access modifier cannot be applied to class and interfaces.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");} }
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Default:
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc. A variable or method declared without any access control modifier is available to any
other class in the same package.
The fields in an interface are implicitly public static final and the methods in an interface are by
MODULE 2: Classes, Methods & Classes OOP- BCS306A
default public.
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
Access within class within outside package by outside package
Modifier package subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
7. Static
It is a keyword which is used to define the class members that will be used independent
of any object of that class. Static members are initialized for the first time when class is loaded.
The most common example of a static member is main( ). main( ) is declared as static because
it must be called before any objects exist.[i.e., without instantiating the class]
Static Methods
Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.
Static Blocks:
Static blocks are also called Static initialization blocks . A static initialization block is a normal
block of code enclosed in braces, { }, and preceded by the static keyword.
static {
// whatever code is needed for initialization goes here
}
class UseStatic
{
static int a = 3;
MODULE 2: Classes, Methods & Classes OOP- BCS306A
static int b;
static
{
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
display (42);
}
}
Static block initialized.
x = 42
a=3
b = 12
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
[Link]("a = " + a);
}
}
class StaticByName
{
public static void main(String args[]) {
[Link]();
[Link]("b = " + StaticDemo.b);
}
}
a = 42
b = 99
Outside of the class in which they are defined, static methods and variables can be used
independently of any object. To do so, you need only specify the name of their class followed by
the dot operator.
MODULE 2: Classes, Methods & Classes OOP- BCS306A
8. Introducing Final
A field can be declared as final. It prevents its contents from being modified, making it, essentially a
constant. It means that a final field when it is declared. It can be done in 2 ways:
Can give it a value when it is declared (most commonly use dmethod)
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;
Can assign it a value within a constructor
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.
Output:
display: outer_x = 100
In the program, an inner class named Inner is defined within the scope of class Outer. Therefore, any
code in class Inner can directly access the variable outer_x. An instance method named display( ) is
defined inside Inner. This method displays outer_x on the standard output stream. The main( ) method
of InnerClassDemo creates an instance of class Outer and invokes its test( ) method. That method
creates an instance of class Inner and the display( ) method is called. It is important to realize that an
instance of Inner can be created only in the context of class Outer. The Java compiler generates an error
message otherwise. In general, an inner class instance is often created by code within its enclosing scope,
as the example does.
It is possible to define inner classes within any block scope. For example, the following program defines
a nested class within the block defined by a method or even within the body for a loop:
Output:
display: outer_x = 100
MODULE 2: Classes, Methods & Classes OOP- BCS306A
The nested classes are not applicable to all situations, they are particularly helpful while handling
events.