0% found this document useful (0 votes)
1 views36 pages

Module 2

The document outlines the curriculum for the Object Oriented Programming with JAVA course (BCS306A) for the academic year 2024-25, detailing class fundamentals, methods, constructors, and object creation. It explains key concepts such as classes as blueprints for objects, the use of the 'new' operator for object instantiation, and the role of constructors in initializing objects. Additionally, it covers the use of the 'this' keyword and provides examples to illustrate these concepts in Java programming.

Uploaded by

surya.91527
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)
1 views36 pages

Module 2

The document outlines the curriculum for the Object Oriented Programming with JAVA course (BCS306A) for the academic year 2024-25, detailing class fundamentals, methods, constructors, and object creation. It explains key concepts such as classes as blueprints for objects, the use of the 'new' operator for object instantiation, and the role of constructors in initializing objects. Additionally, it covers the use of the 'this' keyword and provides examples to illustrate these concepts in Java programming.

Uploaded by

surya.91527
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

REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Object Oriented Programming with JAVA


(BCS306A)
ACADEMIC YEAR 2024 - 25

Lecture notes
Name Of the Programme B.E - CSE

Scheme 2022

Year and Semester II Year III Semester

Subject Code BCS306A

Name of the Faculty Prof SUGUNA.A/Dhivyabharathi.p


Dept of CSE

MODULE II

Introducing Classes: Class Fundamentals, Declaring Objects, Assigning Object Reference


Variables, Introducing Methods, Constructors, 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.

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
➢ CLASS FUNDAMENTALS:
A class is a blueprint or prototype that defines the variables and methods common to
all objects of same kind. A class can be defined as a user-defined data type and an object as a
variable of that data type that can contain data and methods that manipulates the data.
Ex:
Bike
boolean
kickstart
boolean
buttonstart
int gears
accelerate()
applyBrak e()
changeGear()
Fig. Bike class
Manufacturers produce many bikes from the same blueprint as every bike share similar
characteristics. There are many objects of same kind belonging to same classes that share
certain characteristics. Bikes have attributes (speed, engine capacity, number of wheels,
number of gears, brakes) behaviors (braking, accelerating, slowing down, and changing gears).
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 often see the two words object and instance used
interchangeably.
A class is declared by use of the class keyword.
Declaration of class:
class ClassName
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1 (parameter-list)

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
{
// 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.
The instance variables are directly accessible by methods defined in 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.
The data for one object is separate and unique from the data for another.

Example of class:
Create a class structure that may represent the details of Employee .
An employee has several characteristics that you can represent as variables such as
name, salary, etc.
Write a method details () which consists of println() statements that print the values
of instance variables. The Employee class can be defined as follows:
class Employee
{
String name; / / Instance Variables
int salary; / / Instance Variables

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
void details() / / Instance Method
{
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}
➢ CREATING OBJECTS:
• Object is an instance of a class.
• An object is created by creating an instance of a class.
• Creating an object for a class is a two-step process.
o First, 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.
o Second, acquire an actual, physical copy of the object and assign it to that variable by
using the new operator.
• The new operator dynamically allocates memory for an object and returns a reference
to it. This reference is nothing but the address in memory of the object allocated by new. This
reference is then stored in the variable declared.
Syntax for creating an Object :
Classname objectname=new Classname();

Example:
Employee sam=new Employee();
This statement combines the two steps just described. It can be rewritten like this to show each
step more clearly:
Employee sam; // declare reference to object
sam=new Employee(); / / allocate a Employee object
• The first line declares sam as a reference to an object of type Employee.
• After this line executes, sam contains the value null, which indicates that it does not yet
point to an actual object.
• Any attempt to use sam at this point will result in a compile -time error. The next line
allocates an actual object and assigns a reference to it to sam.

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
• After the second line executes , you can use sam as if it were an Employee object. But
sam simply holds the memory address of the actual Employee object.
• The effect of these two lines of code is depicted in Figure :

Statement Effect

Employee sam; sam NULL

Employee

name
sam= new Employee (); sam
salary

Fig : Declaring a Object type sam

Example creating an object and accessing class members via an object:


class Employee
{
String name; // person's name // Instance Variables
double salary; // salary in dollars
void details() / / Instance Method
{
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}
class Demo
{
public static void main(String[] args)
{
Employee ram = new Employee();

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
// may be done on two lines.
//Employee ram; // Object declaration
//ram = new Employee(); // Instantiation
[Link] = "Ram"; // initialization
[Link] = 32000;
// Now print out ram information using details()
[Link]();
}
}
The output produced by this program is shown here:
Name:Ram
Salary:32000
new Operator:

• The new operator dynamically allocates memory for an object. The general form is:
class-var = new classname ( );
• class-var is a variable of the class type being created.
• The classname is the name of the class that is being instantiated. 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.
• Most real-world classes explicitly define their own constructors within their class
definition. However, if no explicit constructor is specified, then Java will automatically supply
a default constructor.
• In example, JVM will initialize the instance variables using a default constructor.
• Java’s primitive types are not implemented as objects and so new operator is not
required for them.
• new allocates memory for an object during run time , so can create as many or as few
objects as needed during the execution .
Assigning Object Reference Variables:
Employee s1=new Employee();
Employee s2=s1;

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
s2 is assigned a reference to a copy of the object referred to by s1. s1 and s2 will both
refer to the same object.
With this assignment, s2 refers to the same object as s1. Thus, any changes made to
the object through s2 will affect the object to which s1 is referring, since they are the same
object.
This situation is depicted here:

name
s1
salary

s2 Employee
A subsequent assignment to s1 will simply unhook s1 from the original object without
affecting the object or affecting s2.
For example:
Employee s1=new Employee();
Employee s2=s1;
// ...
s1 = null;
Here, s1 has been set to null, but s2 still points to the original object.
➢ METHODS:
• Classes usually consist of two things: instance variables and methods.
General form of a method :
type name (parameter -list )
{
// body of method
}
• type specifies the type of data returned by the method. This can be any valid type,
including class types that we create.
• If the method does not return a value, its return type must be void .
• The name of the method is specified by name. This can be any legal identifier other
than those already used by other items within the current scope.
• The parameter -list is a sequence of type and identifier pairs separated by commas.

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

• Parameters are essentially 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 routine
using the following form of the return statement:
return value ;
Here, value is the value returned.
➢ CONSTRUCTORS:
Whenever an object is created for a class, the instance variables of the class need to be
given initial values.
Java allows objects to initialize themselves when they are created. This automatic
initialization is performed using a constructor.
A constructor is a special method which initializes an object immediately upon creation.
It has the same name as the class in which it resides and is syntactically like a method.
When a constructor is not defined for a class, Java compiler provides a default
constructor which automatically initializes all instance variables to their default values.
The constructor is automatically invoked as soon as the object is instantiated with the
new keyword.
Constructors have no return type, not even void. This is because the implicit return type
of a class’ constructor is the class type itself.
If any constructor is defined in the class then the JVM will not provide any constructor.
Example, a simple constructor that simply sets the dimensions of each Box to the same
values.
/* Here, Box uses a constructor to initialize the dimensions of a box.
class Box
{
double width;
double height;
double depth;
Box( )

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
{ // This is the constructor for Box.
[Link]("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume( )
{
// compute and return volume
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[ ])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box( );
Box mybox2 = new Box( );
double vol;
vol = [Link]( ); // get volume of first box
[Link]("Volume is " + vol);
vol = [Link]( ); // get volume of second box
[Link]("Volume is " + vol);
}
}
When this program is run, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
They initialize the details of employee to both mybox1and mybox2.
Parameterized Constructors:
The Box( ) constructor in the preceding example initializes all boxes with the same
dimensions.
Parameters can be passed to a constructor, like having parameters for a method. This
makes them much more useful.
Example:
// Here, Box uses a parameterized constructor to initialize the dimensions of a box.
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)//This is the constructor for Box
{
width = w;
height = h;
depth = d;
}
double volume( )
{
// compute and return volume
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[ ])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = [Link](); //// get volume of first box
[Link]("Volume is " + vol);
vol = [Link](); // get volume of second box
[Link]("Volume is " + vol);
}
}
The output from this program is shown here:
Volume is 3000.0
Volume is 162.0
Each object is initialized with values specified in the parameters to its constructor.
For example, in the following line,
Box mybox1 = new Box(10, 20, 15);
The values 10, 20, and 15 are passed to the Box( ) constructor when new creates the
object. Thus, mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15
respectively.

➢ ‘this’ KEYWORD :
• Java defines the ‘this ’ keyword. this can be used inside any instance method to refer to
the current object.
• this is always a reference to the object on which the method was invoked.
• Example:

Box(double w, double h, double d)


{
// A redundant use of this.
[Link] = w;
[Link] = h;
[Link] = d;
}

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Instance Variable Hiding
It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes.
But the names of local variables, including formal parameters to methods, may overlap
with the names of the class’ instance variables.
So, when a local variable has the same name as an instance variable, the local variable
hides the instance variable.
This is why width, height, and depth were not used as the names of the parameters to
the Box( ) constructor inside the Box class.
Example:
Here is another version of Box( ), which uses width, height, and depth for parameter names
and then uses ‘this’ to access the instance variables by the same name:
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
[Link] = width;
[Link] = height;
[Link] = depth;
}
‘this’ can be used for constructor chaining, means a constructor can be called from
another constructor. Constructor chaining is the process of calling one constructor from
another constructor with respect to current object.
One of the main use of constructor chaining is to avoid duplicate codes while having
multiple constructor (by means of constructor overloading) and make code more
readable.
// Java program to illustrate Constructor Chaining within same class Using this() keyword
class Temp
{
Temp()
{
this(5);

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
[Link]("The Default constructor");
}
Temp(int x)
{
this(5, 15);
[Link](x);
}
Temp(int x, int y)
{
[Link](x * y);
}
public static void main(String args[])
{
// invokes default constructor first
new Temp();
}
}
Output:
75
5
The Default constructor
Rules of constructor chaining :
The this() expression should always be the first line of the constructor.
There should be at-least be one constructor without the this() keyword.
Constructor chaining can be achieved in any order.
➢ OVERLOADING METHODS AND CONSTRUCTORS:
Method overloading is one way of achieving polymorphism in java.
Each method in a class is uniquely identified by its name and parameter list, means
two or more methods with same name, but with a different parameter list. This feature called
as method overloading.
Overloaded methods must differ in the type and/or number of their parameters.

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
When Java encounters a call to an overloaded method, it simply executes the version of
the method whose number and type of parameters match the arguments used in the call.

// Demonstrate method overloading.


class OverloadDemo
{
void test( )
{
[Link]("No parameters");
}
void test(int a)
{
// Overload test for one integer parameter.
[Link]("a: " + a);
}
void test(int a, int b)
{
// Overload test for two integer parameters.
[Link]("a and b: " + a + " " + b);
}
double test(double a)
{
// overload test for a double parameter
[Link]("double a: " + a);
return a*a;
}
}
class Overload
{

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
public static void main(String args[ ])
{
OverloadDemo ob = new OverloadDemo( );
double result;
[Link]();
[Link](10);
[Link](10, 20);
result = [Link](123.25);
[Link]("Result of [Link](123.25): " + result);
}
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of [Link](123.25): 15190.5625
test( ) is overloaded four times. The first version takes no parameters, the second
takes one integer parameter, the third takes two integer parameters, and the fourth takes one
double parameter.
The fact that the fourth version of test( ) also returns a value is of no consequence
relative to overloading since return types do not play a role in overload resolution.
When overloaded method is called, Java looks for a match between the arguments
used to call the method and the method’s parameters.
However, this match need not always be exact. In some cases, Java’s automatic type
conversions can play a role in overload resolution.

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

Example:
// Automatic type conversions apply to overloading.
class OverloadDemo
{
void test()
{
[Link]("No parameters");
}
void test(int a, int b)
{
// Overload test for two integer parameters.
[Link]("a and b: " + a + " " + b);
}
void test(double a)
{
// overload test for a double parameter
[Link]("Inside test(double) a: " + a);
}
}
class Overload
{
public static void main(String args[ ])
{
OverloadDemo ob = new OverloadDemo( );
int i = 88;
[Link]();
[Link](10, 20);
[Link](i); // this will invoke test(double)
[Link](123.2); // this will invoke test(double)
}
}
Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Output:
No parameters a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2
• OverloadDemo does not define test(int). So, java will automatically convert int to double .

OVERLOADING CONSTRUCTORS:
• Like methods constructor can also be overloaded.
• Constructors for a class having the same name as that of class, but with different signatures I.e.,
different number of arguments or different types of arguments.
Example:
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
// This is the constructor for Box.
width = w;
height = h;
depth = d;
}
double volume()
{
// compute and return volume
return width * height * depth;
}
}
The Box( ) constructor requires three parameters. This means that all declarations of Box
objects must pass three arguments to the Box( ) constructor.
For example, the following statement is currently invalid.
Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Box ob = new Box();
because Box( ) requires three arguments.
// Here, Box defines three constructors to initialize the dimensions of a box various ways.
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
//constructor used when all dimensions specified
width = w;
height = h;
depth = d;
}
Box()
{
// constructor used when no dimensions specified
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Box(double len)
{
// constructor used when cube is created
width = height = depth = len;
}
double volume()
{
// compute and return volume
return width * height * depth;
}
Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = [Link](); // get volume of first box
[Link]("Volume of mybox1 is " + vol);
vol = [Link](); // get volume of second box
[Link]. println("Volume of mybox2 is " + vol);
vol = [Link](); // get volume of cube
[Link]("Volume of mycube is " + vol);
}
}

Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0.
Volume of mycube is 343.0
The appropriate overloaded constructor is called based upon the parameters specified when
new is executed.

ACCESS CONTROL :
Encapsulation provides another important attribute: access control. Through encapsulation, we can
control what parts of a program , can access the members of a class.
The access modifiers in Java specifies accessibility (scope) of a data member, method, constructor,
or class.

There are 4 types of Java access modifiers:


Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
◻ private
◻ default
◻ protected
◻ public

protected applies only when inheritance is involved.


When a member of a class is specified as public, 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.
If no access specifier is used, then by default the member of a class is provided default
access level within its own package but cannot be accessed outside of its package.
// This program demonstrates the difference between public and private.
class Test
{
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i)
{
// set c's value
c = i;
}
int getc()
{
return c; // get c's value
}
}
class AccessTest
{
public static void main(String args[])

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
{
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
[Link](100); // OK
[Link]("a, b, and c: " + ob.a + " " + ob.b + " " + [Link]());
}
}
Inside the Test class, a uses default access, which for this example is the same as
specifying public . b is explicitly specified as public .
Member c is given private access. This means that it cannot be accessed by code outside
of its class.
So, inside the AccessTest class, c cannot be used directly. It must be accessed through its
public methods: setc( ) and getc( ) .

1) Private Access Modifier: The private access modifier is accessible only within class.
Example:
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
}
}

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class.
For example:
class A
{
private A()
{
}//private constructor
void msg()
{
[Link]("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();//Compile Time Error
}
}
2) Default Access Modifier
If you don't use any modifier, it is treated as default. The default modifier is accessible onlywithin
package.
Example:
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//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
}
Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
3) Protected Access Modifier
The protected access modifier is used in case of inheritance. The protected access modifier can be
applied on the data member, method, and constructor. It can't be applied on the class.

Example:
In this example, we have created the two packages pack and mypack. The A class of pack package is public,
so can be accessed from outside the package. But msg method of this package is declared as protected, so it
can be accessed from outside the class only through inheritance.
//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]();
}
}
Output:
Hello
4) Public Access Modifier
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example:
//save by [Link]
package pack;
public class A{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output:
Hello

Access Modifier Within Class Within Package Outside Package Outside Package

By Subclass Only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

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.
NOTE that, only the return type of the method is not sufficient for overloading.
class Overload
{
void test( ) //method without any arguments
{
[Link]("No parameters");
}
void test(int a) //method with one integer argument
{
[Link]("Integer a: " + a);
}
void test(int a, int b) //two arguments
{
[Link]("With two arguments : " + a + " " + b);
}
void test(double a) //one argument of double type
{
[Link]("double a: " + a);
}
}
class OverloadDemo
{
public static void main(String args[])
{
Overload ob = new Overload();
[Link]();
[Link](10);
[Link](10, 20);
[Link](123.25);
}
}

Overloading Constructors
One can have more than one constructor for a single class if the number and/or type of arguments are
different. Consider the following code:
class OverloadConstruct
{
int a, b;
OverloadConstruct()

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

{
[Link]("Constructor without arguments");
}
OverloadConstruct(int x)
{
a=x;
[Link]("Constructor with one argument:"+a);
}
OverloadConstruct(int x, int y)
{
a=x;
b=y;
[Link]("Constructor with two arguments:"+ a +"\t"+ b);
}
}
class OverloadConstructDemo
{
public static void main(String args[])
{
OverloadConstruct ob1= new OverloadConstruct();
OverloadConstruct ob2= new OverloadConstruct(10);
OverloadConstruct ob3= new OverloadConstruct(5,12);
}
}

Output:
Constructor without arguments
Constructor with one argument: 10
Constructor with two arguments: 5

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)
Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

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

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

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

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);
Test ob2;
ob2 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
ob2 = [Link]();
[Link]("ob2.a after second increase: " + ob2.a);
}

Output:

ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

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 you pass a primitive type to a method, it is passed by value. When you pass
an object to a method, they are passed by reference. Keep in mind that when you create a
variable of a class type, you are only creating a reference to an object. Thus, when you pass this
reference to a method, the parameter that receives it will refer to the same object as that referred
to by the argument. 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;

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
class CallByRef
{
public static void main(String args[])
{

Test ob = new Test(15, 20);


[Link]("before call: " + ob.a + " " + ob.b);
[Link](ob);
[Link]("after call: " + ob.a + " " + ob.b);
}
}

Output:

before call: 15 20

after call: 30 10

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();
[Link]("Factorial 3 is "+ [Link](3));
[Link]("Factorial 8 is "+ [Link](8));

Output:
Factorial of 3 is 6
Factorial of 8 is 40320

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A

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 of the class share the
same static variable.

Methods declared as static have several restrictions:

• They can only call other static methods.


• They must only access static data.
• They cannot refer to this or super in any way.

class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
[Link]("Inside static method, a = " + a);

} }

class StaticByName
{
public static void main(String args[])
{
[Link]();
[Link]("Inside main, b = " + StaticDemo.b);

} }

Output:
Inside static method, a = 42

Inside main, b = 99

USING FINAL
• The final keyword is used in three ways
- To variables, those become constants.
- To methods, those should not be override.
- To the class, then that class should not be inherited.

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
Program which illustrates the usage of final keyword
/* final keyword to variable,method */
import [Link].*;
class A
{
public int i;
final int SPEED_LIMIT=60;
public A()
{
[Link](" \n \t default constructor A() is called");
i=10;
}
public final void Aadd() // not overrided since final
{
[Link](" \n \t in A class final add() method is called ");
i=i+10;
}
public void Adisplay()
{
[Link](" \n \t in A class i= "+i);
}
}
class B extends A
{
public int j;
public B()
{
[Link] tln("\n \t default constructor B() is called");
j=20;
}
public void Badd()

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
{
[Link](" \n \t in B class Badd() is called");
j=j+i;
}
public void Bdisplay()
{
[Link](" \n \t in B class j= "+j);
}
}
class FinalMethod
{
public static void main(String ar[]) throws IOException
{
[Link](" \n \t start of main()");
B b=new B();
[Link]();
[Link]();
[Link]();
[Link]();
[Link](" \n \t end of main()");
}
}
OUTPUT
start of main()
default constructor A() is called
default constructor B() is called
in A class final add() method is called
in A class i=20
in B class Badd() is called
in B class j=40
end of main()

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
/ * final keyword to class */
import [Link].*;
final class A // not inherited
{
public int i;
public A()
{
[Link](" \n \t default constructor A() is called");
i=10;
}
public final void Aadd() // not overrided since final
{
[Link](" \n \t in A class final add() method is called ");
i=i+10;
}
public void Adisplay()
{
[Link]("\n \t in A class i= "+i);
}
}
class FinalCV
{
public static void main(String ar[]) throws IOException
{
[Link](" \n \t start of main()");
final int f=100; // like const variable
[Link]("\n \t in main() the value of final f= "+f);
A ob=new A();
[Link]();
[Link]();
[Link](" \n \t end of main()");

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
}
}

OUT PUT :
start of main()
in main() the value of final f=100
default constructor A() is called
in A class final add() method is called
in A class i=20
end of main()

Nested and Inner Classes


It is possible to define a class within another class; 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. However, the enclosing class does not have access to the members of the nested
class.
There are two types of nested classes: static and non-static. A static nested class is one
that has the static modifier applied. Because it is static, it must access the members of
its enclosing class through an object. That is, it cannot refer to members of its enclosing
class directly. Because of this restriction, static nested classes are seldom used. The
most important type of nested class is the inner class.
An inner class is a non-static nested class. It has access to all 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.

Example:
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
[Link]();
}
// this is an inner class
class Inner
Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA - BCS306A
{
void display()
{
[Link]("display: outer_x = " + outer_x);
}
}
}

class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
[Link]();
}
}
Output:
display: outer_x = 100

Prof SUGUNA.A/Dhivyabharathi.p Dept of CSE SSCE, Anekal

You might also like