0% found this document useful (0 votes)
10 views32 pages

Module 2

Module 2 of the Object Oriented Programming course covers the fundamentals of classes in Java, including declaring objects, methods, constructors, and garbage collection. It explains the structure of a class, how to instantiate objects, and the importance of methods for accessing and manipulating instance variables. The module also discusses object references, memory management, and the use of parameters in methods to enhance functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views32 pages

Module 2

Module 2 of the Object Oriented Programming course covers the fundamentals of classes in Java, including declaring objects, methods, constructors, and garbage collection. It explains the structure of a class, how to instantiate objects, and the importance of methods for accessing and manipulating instance variables. The module also discusses object references, memory management, and the use of parameters in methods to enhance functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 2: Classes, Methods & Classes OOPS- BCS306A

III Semester

Course: OBJECT ORIENTED PROGRAMMING WITH JAVA


Course Code: BCS306A
Credits: 03 & 2022 Scheme

Module II: Introducing Classes

D
`Dept Of CSE, VIT Page 1
MODULE 2: Classes, Methods & Classes OOPS- BCS306A

Module 2

Introducing Classes: Classes 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, Access Control, Understanding static, Introducing final, Introducing Nested and Inner

Classes.

Chapter 6, 7

D
`Dept Of CSE, VIT Page 2
MODULE 2: Classes, Methods & Classes OOPS- 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.

The General form of a Class

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.

D
`Dept Of CSE, VIT Page 3
MODULE 2: Classes, Methods & Classes OOPS- BCS306A

// A program that uses the Box class.


//[Link]
class Box { double width; double height; double depth;
}
// This class declares an object of type Box.
Class BoxDemo {
public static void main(String args[])
{
Box mybox = new Box();
double vol;

[Link] = 10;
[Link] = 20;
[Link] = 15;

vol = [Link] * [Link] * [Link];


[Link]( + vol);
}
}

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:

// A program that uses the Box class.


//[Link]
class Box { double width; double height; double depth;
}
// This class declares an object of type Box.
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;

D
`Dept Of CSE, VIT Page 4
MODULE 2: Classes, Methods & Classes OOPS- BCS306A

vol = [Link] * [Link] * [Link];


[Link](―Volume is ― + vol);

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’

Declaring Objects/ Instantiating a Class:


Creating objects of a class is a two-step process.

 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.

Box mybox = new Box();

OR
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object

D
`Dept Of CSE, VIT Page 5
MODULE 2: Classes, Methods & Classes OOPS- 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.

Java Heap Space


Java Heap space is used by java runtime to allocate memory to Objects and JRE classes.
Whenever we create any object, it’s always created in the Heap space. Garbage Collection runs
on the heap memory to free the memory used by objects that doesn’t have any reference.

Java Stack Memory


Java Stack memory is used for execution of a thread. They contain method specific values that
are short-lived and references to other objects in the heap that are getting referred from the
method. Stack memory is always referenced in LIFO (Last-In-First-Out) order

D
`Dept Of CSE, VIT Page 6
MODULE 2: Classes, Methods & Classes OOPS – BCS306A

Assigning Object Reference Variables


• Object reference variables act differently than you might expect when an assignment takes place.
Box b1 = new Box();
Box b2 = b1;
• You might think that b2 is being assigned a reference to a copy of the object referred to by b1.
• That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would
be wrong.
• Instead, after 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.
• 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

This is the general form of a method:

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 OOPS – 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;
}

void setDim(double w, double h, double d) {


width = w;
height = h;
depth = d;
}
}

class Demo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

[Link](10, 20, 15);


[Link](3, 6, 9);

vol = [Link]();
[Link](―Volume is ― + vol);

vol = [Link]();
[Link](―Volume is ― + vol);
}
}

Adding a Method to the Box Class

• 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.
MODULE 2: Classes, Methods & Classes OOPS – 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;

//display volume of first box


[Link]();
//display volume of second box
[Link]();

}
}
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.
MODULE 2: Classes, Methods & Classes OOPS – 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.
MODULE 2: Classes, Methods & Classes OOPS – BCS306A

• There are two important things to understand about returning values:


1) The type of data returned by a method must be compatible 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.
2) The variable receiving the value returned by a method (such as vol, in this case) must also
be compatible with the return type specified for the method.

Adding a Method That Takes Parameters

• 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.
MODULE 2: Classes, Methods & Classes OOPS – 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;

[Link](10, 20, 15);


[Link](3, 6, 9);

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.

A constructor is called automatically when a new instance of an object is created.


MODULE 2: Classes, Methods & Classes OOPS – BCS306A

There are two types of constructors:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Default Constructor: It is a constructor which do not take any [Link] you do not
define any constructor in your class, java generates one for you by default.

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);
}
}
MODULE 2: Classes, Classes & Methods OOP – BCS306A

Parameterized constructor

A constructor that have parameters is known as 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.

The this Keyword


Java defines the this keyword. It can be used inside any method to refer to the current object.

Box(double w, double h, double d)


{
[Link] = w;
[Link] = h;
[Link] = d;
}
 this keyword is used to refer to current object.
 this is always a reference to the object on which method was invoked.
 this can be used to invoke current class constructor.
 this can be passed as an argument to another method.
MODULE 2: Classes, Classes & Methods OOP – BCS306A

Instance Variable Hiding:

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);
}

public static void main(String args[])


{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}

Role of this () in constructor overloading


/*this() is used for calling the default constructor from parameterized constructor. It should
always be the first statement in constructor body. */

public class student


{
private int rollNum;
student()
{
rollNum =100;
}
student(int rnum)
{
this();
rollNum = rollNum+ rnum;
}
public int getRollNum() {
return rollNum;
}
public void setRollNum(int rollNum) {
[Link] = rollNum;
}
}
class TestDemo{
public static void main(String args[])
{
student obj = new student(12);
[Link]([Link]());
}
}
MODULE 2: Classes, Classes & Methods OOP – BCS306A

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:

protected void finalize()


{
//code
}

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.

public class TestGarbage1{


public void finalize(){[Link]("object is garbage collected");}
public static void main(String args[]){ TestGarbage1 s1=new
TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
[Link]();
}
}
object is garbage collected
object is garbage collected

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

void push(int item)


{
if(top==9)
[Link]("Stack is full.");
else
stck[++top] = item;
}

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();

// push some numbers onto the


stack for(int i=0; i<10; i++)
[Link](i);
for(int i=10; i<20;
i++) [Link](i);

[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

Chapter 2: Methods and Classes

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

Advantage of method overloading


1) Method overloading increases the readability of the program.

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.

[Link] (4.6f, 3.8f); //sum(float a, float b) is called.


}
}
Sum is 13
Sum is 8.4

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

2. Using Objects as Parameters


It is both correct and common to pass objects to methods. For example, consider the following
short program:
// Objects may be passed to methods.
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 equals(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));
}
}

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

void meth(int i, int j)


{
i*=2;
j/=2;
}
}
class CallByValue
{
public static void main(String[] args)
{
Test ob=new Test();
int a=15, b=20;
[Link](“a and b before call: “ +a+ “ “ +b);
[Link](a,b);
[Link](“a and b after call: “ +a+ “ “ +b);
}
}
Output:
a and b before call: 15 20
a and b after call: 15 20

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

[Link](“ob2.a after second increase: “+ob2.a);


}
}

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();

[Link]("Factorial of 3 is " + [Link](3));


[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}

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");}
}

public class Simple


.{
. public static void main(String args[])
{
A obj=new A();
[Link]([Link]); //Compile Time Error
[Link](); //Compile Time Error
}
}

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 void display (int x)


{
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + 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.

9. Nested and Inner Classes


A class within another class 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. There are two types of nested classes: static and non-static.
a. A static nested class is one that has the static modifier applied. Because it is static, 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.
b. Second type is ‘inner’ class. 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.

//Demonstrate an inner class


Class Outer
{
int outer_x=100;
void test()
{
Inner inner=new Inner();
[Link]();
}

//this is an inner class


class Inner
{
void display()
{
[Link](“display: outer_x= “ +outer_x);
}
}
}
Class InnerClassDemo
{
MODULE 2: Classes, Methods & Classes OOP- BCS306A

Public static void main(String[] args)


{
Outer outer =new Outer();
[Link]();
}
}

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:

//Define an inner class within a for loop


Class Outer
{
int outer_x=100;
void test()
{
for(int i=0;i<10;i++)
{
class Inner
{
void display()
{
[Link](“display: outer_x= “ +outer_x);
}
}
Inner inner = new Inner();
[Link]();
}}
}
Class InnerClassDemo
{
public static void main(String[] args)
{
Outer outer =new Outer();
[Link]();
}
}

Output:
display: outer_x = 100
MODULE 2: Classes, Methods & Classes OOP- BCS306A

display: outer_x = 100


display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100

The nested classes are not applicable to all situations, they are particularly helpful while handling
events.

You might also like