[go: up one dir, main page]

0% found this document useful (0 votes)
4 views39 pages

OOPJ(java) Unit-II

The document outlines the concepts of classes and objects in Java, including class declaration, object creation, access control, and the use of constructors. It explains the differences between classes and objects, access modifiers, and the characteristics of objects. Additionally, it provides examples of code illustrating these concepts and their applications in object-oriented programming.
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)
4 views39 pages

OOPJ(java) Unit-II

The document outlines the concepts of classes and objects in Java, including class declaration, object creation, access control, and the use of constructors. It explains the differences between classes and objects, access modifiers, and the characteristics of objects. Additionally, it provides examples of code illustrating these concepts and their applications in object-oriented programming.
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
You are on page 1/ 39

S.

No Name of the Topic Page No Date

Chapter I Classes and Objects


2.1 Introduction, Class Declaration and Modifiers, Class Members 2-6
2.2 Declaration of Class Objects 6-7
2.3 Assigning One Object to Another 7-8
2.4 Access Control for Class Members 9-10
2.5 Accessing Private Members of Class 11-12
2.6 Constructor Methods for Class 13-15
2.7 Overloaded Constructor Methods 16-17
2.8 Nested Classes 18-19
2.9 Final Class and Methods 19-20
2.10 Passing Arguments by Value and by Reference 21-22
2.11 Keyword this 23-25
Chapter II Methods
2.12 Introduction, Defining Methods 26-28
2.13 Overloaded Methods 29-30
2.14 Overloaded Constructor Methods 16-17
2.15 Class Objects as Parameters in Methods 31
2.16 Access Control 11-12
2.17 Recursive Methods 32-33
2.18 Nesting of Methods 34-35
2.19 Overriding Methods 36-37
2.20 Attributes Final and Static 38-39
Unit-II
Chapter I Classes and Objects
2.1 Introduction, Class Declaration and Modifiers, Class Members
Class:
Class is a blue print which is containing only list of variables and methods. When we declare a class no
memory is allocated. A class in java contains:
 Data Members
 Methods
 Constructors
 Blocks
 Class and Interface
Syntax-Declaration of class
class Class_Name
{
data members;
methods;
}
Object:
 Object is a instance (allocating memory) of class and object has state and behaviors.
 The objectName must begin with an alphabet, and a Lower-case letter is preferred.
 We can create any no. Of objects for any class
An Object in java has three characteristics:
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is classically implemented via a unique ID.
Syntax
<ClassName> <objectName> = new <ClassName>( );

Simple Example
class Ex1
{
int a;
public static void main(String args[])
{
Ex1 e = new Ex1();
e.a = 10;
System.out.println(" number= "+e.a);
}
}
Output: number=10

Object Oriented Programming Through Java Page 2


Difference between Class and Object

Class Object

Class is a container which collection of


1 object is a instance of class
variables and methods.

No memory is allocated at the time of Sufficient memory space will be allocated for all
2
declaration the variables of class at the time of declaration.

One class definition should exist only once in


3 For one class multiple objects can be created.
the program.

b) Access Modifiers-Access specifiers


 In java, the access modifiers define the accessibility(visibility) of the class and its members.
 Java has four access modifiers, and they are default, private, protected, and public.
 The class acts as a container of data and methods. So, the access modifier decides the
accessibility of class members across the different packages.

 The public members can be accessed everywhere.


 The private members can be accessed only inside the same class.
 The protected members are accessible to every child class (same package or other packages).
 The default members are accessible within the same package but not outside the package.
Example
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
Object Oriented Programming Through Java Page 3
void showData()
{
System.out.println(" Inside ParentClass ");
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" c = " + c);
System.out.println(" d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}
}
c) Class members
 The class members declared in the body of a class . These may contain fields(variables in a class) ,
methods, nested classes and interfaces.
 The members of a class contain the members declared in the class as well as the members inherited from
a super class
 The scope of all the members extends to the entire class body

Object Oriented Programming Through Java Page 4


The filelds contains two types of variables:
Non-static variables : these include local and instance variables which vary in scope and value
a)Instance variables : these variables are individuals to an object and an object keeps a copy of these
variables in its memory
b)Local variables : These are local in scope and not accessible outside their scope
Static or class variables :
 The values of these variables are common to all the objects of the class.
 The class keeps only one copy of these variables and all the objects share the same copy. As class
variables belongs to the whole class, these are also called class variables .
Program:
public class StaticExample
{
static int a = 10; // Static variable
int b = 20; // Non-static variable

public static void staticMethod() // Static method


{
System.out.println("This is a static method.");

System.out.println("Static variable staticVar: " + a); // using static variable within static method

// Cannot access non-static variables directly within a static method


// System.out.println("Non-static variable nonStaticVar: " + b); // This would cause CE
}

public void nonStaticMethod() // Non-static method


{
System.out.println("This is a non-static method.");
System.out.println("Static variable staticVar: " + a);
// Accessing both static and non-static variables within non-static method
System.out.println("Non-static variable nonStaticVar: " + b);
}
public static void main(String[] args)
{
staticMethod(); // Calling static method
StaticExample obj = new StaticExample(); // Creating object of class to call non-static method
obj.nonStaticMethod();

System.out.println("Accessing static variable using class name: " + StaticExample.a);


// Cannot access non-static variable directly using class name
// System.out.println("Accessing non-static variable using class name: " + StaticExample.b); // CE
}
}

Object Oriented Programming Through Java Page 5


Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac StaticExample.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java StaticExample
This is a static method.
Static variable staticVar: 10
This is a non-static method.
Static variable staticVar: 10
Non-static variable nonStaticVar: 20
Accessing static variable using class name: 10
2.2 Declaration of Class Objects
Declare a class object with class identifier (class name)
Syntax:
Classname object_name;
Example:
class Student
{
int rollno;
String name; // String is a class name is object type of variable
void insertRecord(int r , String n)
{
rollno = r;
name = n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}

class TestStudent4
{
public static void main (String args[])
{
Student s1 = new Student();
Student s2 = new Student();

s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");

s1.displayInformation();
s2.displayInformation();
}
}

Object Oriented Programming Through Java Page 6


Output:
111 Karan
222 Aryan

 As you can see in the above figure, object gets the memory in heap memory area.
 The reference variable refers to the object allocated in the heap memory area.
 Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
2.3 Assigning One Object to Another
 In Java, assigning one object to another involves copying the reference(address) of the object, not the
object itself.
 This means that both references (addresses) will point to the same object in memory, so changes made
through one reference will be reflected in the other.
Example:
class Student1
{
int rollno;
String name; // String is a class name is object type of variable
void insertRecord(int r , String n)
{
rollno = r;
name = n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}

Object Oriented Programming Through Java Page 7


class TestStudent5
{
public static void main (String args[])
{
Student1 s1 = new Student1();
Student1 s2 = new Student1();

s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");

s1.displayInformation();
s2.displayInformation();

s2=s1; // assigning one obj to another obj

s1.name="sunil"; // changes made in one obj will reflect in another

s1.displayInformation();
s2.displayInformation();
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\cseb_codes>javac TestStudent5.java
D:\acem 2024-25 OOPJ CSE A&B\cseb_codes>java TestStudent5
111 Karan
222 Aryan
111 sunil
111 sunil

Object Oriented Programming Through Java Page 8


2.4 Access Control for Class Members
Access level modifiers determine whether other classes can use a particular field or call a particular method.
There are two levels of access control:
 At the top level—public, or package-private (no explicit modifier).
 At the member level—public, private, protected, or package-private (no explicit modifier).
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere.
At the top level:
If a class has no modifier (the default, also known as package-private), it is visible only within its own
package (packages are named groups of related classes )
At the member level:
At the member level, you can also use the public modifier or no modifier (package-private) just as with
top-level classes, and with the same meaning.
 For members, there are two additional access modifiers: private and protected.
 The private modifier specifies that the member can only be accessed in its own class.
 The protected modifier specifies that the member can only be accessed within its own package (as
with package-private) and, in addition, by a subclass of its class in another package.
The following table shows the access to members permitted by each modifier.
Access Levels

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

 The first data column indicates whether the class itself has access to the member defined by the access
level.
 As you can see, a class always has access to its own members.
 The second column indicates whether classes in the same package as the class (regardless of their
parentage) have access to the member.
 The third column indicates whether subclasses of the class declared outside this package have access to
the member.
 The fourth column indicates whether all classes have access to the member.
Let's look at a collection of classes and see how access levels affect visibility. The following figure shows the
four classes in this example and how they are related.

Object Oriented Programming Through Java Page 9


Classes and Packages of the Example Used to Illustrate Access Levels

The following table shows where the members of the Alpha class are visible for each of the access modifiers
that can be applied to them.

Visibility

Modifier Alpha Beta Alphasub Gamma

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

Tips on Choosing an Access Level:


If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels
can help you do this.
 Use the most restrictive access level that makes sense for a particular member. Use private unless you
have a good reason not to.
 Avoid public fields except for constants. Public fields have a susceptibility to link you to a particular
implementation and limit your give in changing your code.

Object Oriented Programming Through Java Page 10


2.5 Accessing Private Members of Class
Accessing Private variable of Class
private members of a a class , whether they are instance variables or methods , can only accessed by other
members of a same class. Any outside code cannot directly access them.
Code :
class Farm
{
private double length; //private variable
private double width; //private variable

double area()
{
return length*width;
}

void setSides(double l, double w)


{
length = l;
Width = w;
}

double getLength()
{
return length;
}

double getWidth()
{
return width;
}
}
class AccessPrivateTechnique
{
public static void main(String[] args)
{
Farm f = new Farm();
f.setSides(50.0,20.0);
System.out.println("length = "+f.getLength()); // accessing private variable
System.out.println("length = "+f.getWidth()); // accessing private variable
System.out.println("area = "+f.area());
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac AccessPrivateTechnique.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java AccessPrivateTechnique
length = 50.0
length = 20.0
area = 1000.0

Object Oriented Programming Through Java Page 11


Accessing Private method of Class
We can declare methods as private if our intention is to hide implementation from the user .
Code:
class Farm1
{
private double length;
private double width;

private double area()


{
return length*width;
}
void setSides(double l,double w)
{
length = l;
width = w;
}

double getLength()
{
return length;
}

double getWidth()
{
return width;
}
double getArea()
{
return area();
}
}

class AccessPrivateTechnique2
{
public static void main(String[] args)
{
Farm1 f = new Farm1();
f.setSides(50.0,20.0);
System.out.println("length = "+f.getLength());
System.out.println("length = "+f.getWidth());
System.out.println("area = "+f.getArea());
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac AccessPrivateTechnique2.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java AccessPrivateTechnique2
length = 50.0
length = 20.0
area = 1000.0

Object Oriented Programming Through Java Page 12


2.6 Constructor Methods for Class
Constructors
 Constructor is a special type of method and Constructor name must be same as its class name
 Constructor is used to initialize the object.
 constructor is invoked (called) automatically when we create the object creation.
 It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.


 Constructor name must be same as its class name
 Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
 Default constructor (no-arg constructor)
 Parameterized constructor

Default Constructor
 A constructor is said to be default constructor if and only if it never take any parameters.
 If any class does not contain at least one user defined constructor than the system will create a default
constructor at the time of compilation it is known as system defined default constructor.
Syntax

class className
{
className () // Call default constructor
{
Block of statements; // Initialization
}
}

Note:

System defined default constructor is created by java compiler and does not have any statement in the body
part.
This constructor will be executed every time whenever an object is created if that class does not contain any
user defined constructor.

Object Oriented Programming Through Java Page 13


Example :
//TestDemo.java
class Test
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
}
class TestDemo
{
public static void main(String [] args)
{
Test t1=new Test ();
}
}
Output:
I am from default Constructor...
Value of a: 10
Value of b: 20

parameterized constructor
 If any constructor contain list of variable in its signature is known as paremetrized constructor.
 A parameterized constructor is one which takes some parameters.
Syntax
class ClassName
{
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}
Syntax : ClassName objref = new ClassName(value1, value2,.....);

Object Oriented Programming Through Java Page 14


Example
class Test
{
int a, b;
Test(int n1, int n2)
{
System.out.println("I am from Parameterized Constructor...");
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
}
class TestDemo1
{
public static void main(String k [])
{
Test t1=new Test(10, 20);
Test t2=new Test(4,5);
}
}
Output:
I am from Parameterized Constructor...
Value of a = 10
Value of b = 20
I am from Parameterized Constructor...
Value of a = 4
Value of b = 5

Object Oriented Programming Through Java Page 15


2.7 Overloaded Constructor Methods
 Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.
 The compiler differentiates these constructors by taking the number of parameters, and their type.
 In other words whenever same constructor is existing multiple times in the same class with different
number of parameters or order of parameters or type of parameters is known asConstructor overloading.
Syntax

class ClassName
{
ClassName()
{
..........
}
ClassName(datatype1 value1)
{
.......
}
ClassName(datatype1 value1, datatype2 value2)
{
.......
}
ClassName(datatype2 variable2)
{
.......
}
}

Object Oriented Programming Through Java Page 16


Example (week 3 code (d))

public class ConstructorOverloading


{

ConstructorOverloading(int a , int b)
{
System.out.println("addition of integers with 2 params ="+(a+b));

ConstructorOverloading(int a , int b, int c)


{
System.out.println("addition of integers with 3 params ="+(a+b+c));
}

ConstructorOverloading(double a , double b)
{
System.out.println("addition of doubles with 2 params ="+(a+b));
}
ConstructorOverloading(String a , String b)
{
System.out.println("addition of strings with 2 params ="+(a+b));
}

public static void main(String[] args)


{
ConstructorOverloading c1 = new ConstructorOverloading(5,10);
ConstructorOverloading c2 = new ConstructorOverloading(5,10,15);
ConstructorOverloading c3 = new ConstructorOverloading(2.5,3.5);
ConstructorOverloading c4 = new ConstructorOverloading("Good","Luck");
}
}
Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac ConstructorOverloading.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java ConstructorOverloading
addition of integers with 2 params =15
addition of integers with 3 params =30
addition of doubles with 2 params =6.0
addition of strings with 2 params =GoodLuck

Object Oriented Programming Through Java Page 17


2.8 Nested Classes
 Java inner class or nested class is a class that is declared inside the class or interface.
 Additionally, it can access all the members of the outer class, including private data members and
methods.
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Need of Java Inner class
 Sometimes users need to program a class in such a way so that no other class can access it. Therefore, it
would be better if you include it within other classes.
 If all the class objects are a part of the outer object then it is easier to nest that class inside the outer
class. That way all the outer class can access all the objects of the inner class.
Java Member Inner class
 A non-static class that is created inside a class but outside a method is called member inner class.
 It is also known as a regular inner class. It can be declared with access modifiers like public, default,
private, and protected.
Example:
Here, msg() method in the member inner class that is accessing the private data member of the outer class.
TestMemberOuter1.java
class TestMemberOuter1
{
private int data = 30;
class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}

public static void main(String args[])


{
TestMemberOuter1 obj = new TestMemberOuter1();
TestMemberOuter1.Inner in = obj.new Inner(); // object creation
in.msg();
}
}

Object Oriented Programming Through Java Page 18


Output:

D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac TestMemberOuter1.java


D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java TestMemberOuter1
data is 30

Internal working of Java member inner class


 The java compiler creates two class files in the case of the inner class.
 The class file name of the inner class is "Outer$Inner".
 If you want to instantiate the inner class, you must have to create the instance of the outer class. In such
a case, an instance of inner class is created inside the instance of the outer class.

2.9 Final Class and Methods


Java final class
If you make any class as final, you cannot extend it.
Example
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda = new Honda1();
honda.run();
}
}

Output: Compile Time Error

Object Oriented Programming Through Java Page 19


Java final method

If you make any method as final, you cannot override it.

Example :
class Bike
{
final void run()
{
System.out.println("running");
}
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda = new Honda();
honda.run();
}
}
Output: Compile Time Error

Object Oriented Programming Through Java Page 20


2.10 Passing Arguments by Value and by Reference (Parameter Passing Techniques in Java)
 There are different ways in which parameter data can be passed into and out of methods and functions
 Let us assume that a function B() is called from another function A().
 In this case A is called the “caller function” and B is called the “called function function”.
 The arguments which A sends to B are called actual arguments and the parameters of B are
called formal arguments.
Pass by Value:
In the pass by value concept, the method is called by passing a value. So, it is called pass by value. It
does not affect the original parameter.
Example: // Call by Value
class CallByValue
{
public static void Example(int x, int y) // Function to change the value of the parameters
{
x++;
y++;
}
}

public class Main


{
public static void main(String[] args)
{
int a = 10;
int b = 20;

CallByValue object = new CallByValue();


System.out.println("Value of a: " + a + " & b: " + b);
object.Example(a, b); // Passing variables in the class function
System.out.println("Value of a: "+ a + " & b: " + b); // Displaying values after calling the function
}
}
Output:
Value of a: 10 & b: 20
Value of a: 10 & b: 20

Object Oriented Programming Through Java Page 21


Pass by Reference:
 In the pass by reference concept, the method is called using a reference of the actual parameter.
So, it is called pass by reference.
 It forwards the unique identifier of the object to the method.
 If we made changes to the parameter's instance member, it would affect the original value.
Note: Java does not support pass by reference concept.

Example:

class CallByReference
{
int a, b;

CallByReference(int x, int y) // Function to assign the value to the class variables


{
a = x;
b = y;
}
void ChangeValue(CallByReference obj) // Changing the values of class variables
{
obj.a += 10;
obj.b += 20;
}
}

public class B
{
public static void main(String[] args)
{
CallByReference object = new CallByReference(10, 20);
System.out.println("Value of a: " + object.a+ " & b: "+ object.b);
object.ChangeValue(object);// Changing values in class function
System.out.println("Value of a: " + object.a + " & b: "+ object.b); // print values after calling
}
}
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40

Please note that when we pass a reference, a new reference variable to the same object is created.
So we can only change members of the object whose reference is passed. We cannot change the reference to
refer to some other object as the received reference is a copy of the original reference.

Object Oriented Programming Through Java Page 22


2.11 Keyword this
In Java, this is a reference variable that refers to the current object.
Usage of Java this keyword
Here is given the 3 usage of java this keyword.
1. To refer current class instance variable
2. To invoke current class method
3. To invoke current class constructor
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Note:
If parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish
local variable and instance variable.
Example:
class Robo
{
int x, y , total;
void add(int x , int y)
{
this.x = x;
this.y = y;
total = x+y;
System.out.println("sum= "+total);
}
}
class Mrobo
{
public static void main(String args[])
{
Robo r = new Robo();
r.add(20,30);
}
}
Note:
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword
like in the following program:

Object Oriented Programming Through Java Page 23


2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.

class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m(); //same as this.m()
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a = new A();
a.n();
}
}
Output:
hello n
hello m

3) this() : to invoke current class constructor

 The this() constructor call can be used to invoke the current class constructor.
 It is used to reuse the constructor. In other words, it is used for constructor chaining.
 Rule: Call to this() must be the first statement in constructor.

Object Oriented Programming Through Java Page 24


Calling default constructor from parameterized constructor:
class A
{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5
{
public static void main(String args[])
{
A a = new A(10);
}
}
Output:
hello a
10
Calling parameterized constructor from default constructor:

class A
{
A()
{
this(5);
System.out.println("hello a");
}
A(int x)
{
System.out.println(x);
}
}
class TestThis6
{
public static void main(String args[])
{
A a=new A();
}
}
Output:
5
hello a

Object Oriented Programming Through Java Page 25


2.12 Introduction, Defining Methods
Definition:

 A method is a block of statements which are used to perform a specific task .


 Method gets executes only when it is called.
 Every method in java must be declared inside a class.
 The major advantage of methods is code re-usability (define the code once, and use it many times).

Method Declaration

It has six components that are known as method header

Method Signature:
Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Return Type:
Return type is a data type that the method returns.
It may have a primitive data type, object, collection, void, etc.
If the method does not return anything, we use void keyword.
Method Name:
It is a unique name that is used to define the name of a method.
Parameter List:
It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name.
If the method has no parameter, left the parentheses blank.
Method Body:
It is a part of the method declaration.
It contains all the actions to be performed. It is enclosed within the pair of curly braces.

Object Oriented Programming Through Java Page 26


Types of Methods
There are two types of methods in Java:
 Predefined Method
 User-defined Method

Predefined Methods

 As the name gives it, predefined methods in Java are the ones that the Java class libraries already define.
 This means that they can be called and used anywhere in our program without defining them.
 There are many predefined methods, such as length(), sqrt(), max(), and print(), and each of them is
defined inside their respective classes.

Output:
The Square root is : 5
Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.print("The maximum number is: " + Math.max(9,7)); // using max() method of Math class

}
}
Output: The maximum number is: 9

Object Oriented Programming Through Java Page 27


User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. The calling of a method in a program is simple.
When we call or invoke(call) a user-defined method, the program control transfer to the called method.
Syntax
<Objectname>.methodname(actualarguments);

//Example1

class A
{
int a,b,c;
void sum()
{
a=10;
b=20;
c=a+b;
System.out.println(" c= "+c);
}
}
class B
{
public static void main(String ars[])
{
A e = new A();
e.sum();
}
}

Output:
c=30

Object Oriented Programming Through Java Page 28


2.13 Overloaded Methods (METHODS OVERLOADING)
 class have multiple methods with same name but difference in parameters is called method overloading.
 If we have to perform only one operation, having same name of the methods increases the readability of
the program.
Syntax
class class_Name
{
returntype method(datatype1 variable1)
{
...........
...........
}
returntype method(datatype1 variable1, datatype2 variable2)
{
...........
...........
}
returntype method(datatype2 variable2)
{
...........
...........
}
}
Different ways to overload the method
There are two ways to overload the method in java a) By changing number of arguments or parameters
b) By changing the data type
Example By changing number of arguments
class Addition
{
void sum(int a, int b) // addition of two numbers
{
System.out.println(a+b);
}
void sum(int a, int b, int c) addition of three numbers
{
System.out.println(a+b+c);
}

public static void main(String args[])


{
Addition obj = new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}
Output
30
60

Object Oriented Programming Through Java Page 29


Example By changing the data type
In this example, we have created two overloaded methods that differs in data type.
The first sum method receives two integer arguments and second sum method receives two float arguments.

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}

public static void main(String args[])


{
Addition obj = new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}
Output
30
25.25
Example By changing the data type order
In this example, we have created two overloaded methods that differs in data type order.
The first sum method receives one integer, one float argument and second sum method receives one float and
one integer argument.
class Addition
{
void sum(int a, float b)
{
System.out.println(a+b);
}
void sum(float a, int b)
{
System.out.println(a+b);
}

public static void main(String args[])


{
Addition obj = new Addition();
obj.sum(10, 20.50f);
obj.sum(10.05f, 15);
}
}
Output :
30.5
25.05

Object Oriented Programming Through Java Page 30


2.14 Overloaded Constructor Methods (refer 2.7)
2.15 Class Objects as Parameters in Methods
 Similar to primitive types, Java makes it easier to give objects as parameters to methods.
 It is critical to recognize that sending an object as an argument transmits merely a reference to the item-
not a duplicate of it.
 It means that any changes made to the object inside the method will have an immediate impact on the
original object.
Code Reusability and Modularity:
 Object passing enhances code reusability.
 Promotes modularity by allowing methods to operate on different object instances.
Example:
public class ObjectParameter
{
private int attribute1;
private String attribute2;
private double attribute3;

// Constructor
public ObjectParameter(int attribute1, String attribute2, double attribute3)
{
this.attribute1 = attribute1;
this.attribute2 = attribute2;
this.attribute3 = attribute3;
}

public void myMethod(ObjectParameter obj)


{
System.out.println("Attribute 1: " + obj.attribute1);
System.out.println("Attribute 2: " + obj.attribute2);
System.out.println("Attribute 3: " + obj.attribute3);
}

public static void main(String[] args)


{
ObjectParameter myObject1 = new ObjectParameter(10, "Hello", 3.14);
ObjectParameter myObject2 = new ObjectParameter(20, "World", 6.28);
myObject1.myMethod(myObject2);
}
}
Output:
Attribute 1: 20
Attribute 2: World
Attribute 3: 6.28

Object Oriented Programming Through Java Page 31


2.16 Access Control (Refer 2.5)
2.17 Recursive Methods
The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function.
What is the difference between direct and indirect recursion?
 A function fun is called direct recursive if it calls the same function fun.
 A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun
directly or indirectly.
Direct recursion:
void directRecFun()
{
// Some code....

directRecFun();

// Some code...
}

Indirect recursion:

void indirectRecFun1()
{
// Some code...

indirectRecFun2();

// Some code...
}

void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}

Syntax:

returntype methodname()
{
//code to be executed
methodname();//calling same method
}

Object Oriented Programming Through Java Page 32


Java Recursion Example : Factorial Number
public class RecursionExample3
{
static int factorial(int n)
{
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args)
{
System.out.println("Factorial of 3 is: "+factorial(3));
}
}
Output: Factorial of 3 is: 6

Working of above program:


factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6

Java Recursion Example : Fibonacci Series


public class RecursionExample4
{
static int n1=0,n2=1,n3=0;
static void printFibo(int count)
{
if(count>0)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1);
}
}
public static void main(String[] args)
{
int count=15;
System.out.print(n1+" "+n2); //printing 0 and 1
printFibo(count-2); //n-2 because 2 numbers are already printed
}
}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Object Oriented Programming Through Java Page 33


2.18 Nesting of Methods
 In Java, methods and variables that are defined within a class can only be accessed by creating an object
(object (if non static ) of that class or by using the class name( if the methods are static).
 The dot operator is used to access methods and variables within a class.
 However, there is an exception to this rule: a method can also be called by another method using the
class name, but only if both methods are present in the same class.
 Efficient code organization and simplified method calls within a class are possible through nesting of
methods..
Syntax:
class Main
{
method1()
{
// statements
}
method2()
{
// statements
method1(); // calling method1() from method2()
}
method3()
{
// statements
method2(); // calling of method2() from method3()
}
}
Example :
import java.util.Scanner;

public class NestingMethodsExample


{
int perimeter (int a, int y) // Method to calculate the perimeter of a rectangle
{
int p = 4 * (a + y);
return p;
}

int area(int a, int y) // Method to calculate the area of a rectangle, using the perimeter method
{

int p = perimeter(a, y); // Calling perimeter method to calculate perimeter


System.out.println("Perimeter: " + p);

int r = a * y; // Calculating area


return r;
}

Object Oriented Programming Through Java Page 34


int volume(int a, int y, int h) // Method to calculate the volume of a cuboid, using the area method
{
int r = area(a, y); // Calling area method to calculate area
System.out.println("Area: " + r);

int v = a * y * h; // Calculating volume


return v;
}

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);

System.out.print("Length of the rectangle: ");


int a = scanner.nextInt();

System.out.print("Breadth of the rectangle: ");


Int y = scanner.nextInt();

System.out.print("Height of the cuboid: ");


int h = scanner.nextInt();

NestingMethodsExample obj = new NestingMethodsExample();

int volume = obj.volume(a, y, h); // Calling volume method to calculate volume

System.out.println("Volume: " + volume); // Printing volume


}
}

Output:
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac NestingMethodsExample.java
D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java NestingMethodsExample
Length of the rectangle: 3
Breadth of the rectangle: 4
Height of the cuboid: 5
Perimeter: 28
Area: 12
Volume: 60

Object Oriented Programming Through Java Page 35


2.19 Overriding Methods
Definition: If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.
Usage:
 Method overriding is used to provide our own implementation of a method which is already provided by
its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).

class Vehicle
{
void run()
{
System.out.println(" Vehicle is running ");
}
}

class Bike extends Vehicle


{
public static void main(String args[])
{
Bike obj = new Bike();
obj.run();
}
}
Output:
Vehicle is running

Problem is that I have to provide my own implementation for run() method in subclass that is why we use
method overriding.
The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there
is method overriding.

Object Oriented Programming Through Java Page 36


Example:
class Vehicle
{
void run() //defining a method
{
System.out.println(" Vehicle is running ");
}
}

class Bike2 extends Vehicle


{
void run() //defining the same method as in the parent class
{
System.out.println(" Bike is running safely ");
}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
Output:
Bike is running safely
Difference between method overloading and method overriding in java

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already provided by
its super class.

2) Method overloading is performed within Method overriding occurs in two classesthat have IS-A
class. (inheritance) relationship.

3) In method overloading, parameter must be In case of method overriding, parameter must be same.
different.

4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.

5) In java, method overloading can't be Return type must be same or covariant in method
performed by changing return type of the overriding.
method only. Return type can be same or
Object Oriented Programming Through Java Page 37
different in method overloading. But you
2.20 Attributes Final and Static
Attributes Final
 The final keyword in java is used to restrict the user.
 The java final keyword can be used in many context.
 final can be used for variables or methods or classes
Java final variable
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Example:
class Bike9
{
final int speedlimit = 90; //final variable
void run()
{
speedlimit = 400;
}
public static void main(String args[])
{
Bike9 obj = new Bike9();
obj.run();
}
}
Output: Compile Time Error

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.

Object Oriented Programming Through Java Page 38


Static method :
If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.
Program:

class ExampleStatic
{

static void change() // static method


{
System.out.println("This is static method ");
}
void display() // non static method
{
System.out.println("This is non-static method ");
}

public class TestStaticMethod


{
public static void main(String args[])
{
ExampleStatic.change(); // static method calling

ExampleStatic s1 = new ExampleStatic();

s1.display(); // non static method calling

}
}

Output :

D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac TestStaticMethod.java


D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java TestStaticMethod
This is static method
This is non-static method

Object Oriented Programming Through Java Page 39

You might also like