You are on page 1of 28

UNIT 2

Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Constructor Methods, Nested Classes, Final Class and Methods,
Passing Arguments by Value and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor
Methods, Recursive Methods, Nesting of Methods, Overriding Methods, Attributes Final and
Static.
2.1 Classes and Objects Introduction
Classes:
• A class is a group of objects which have common properties.
• It is a template or blueprint from which objects are created.
• Classes are user-defined data types and behave like the built-in types of a programming
language.
• It is a logical entity. It can't be physical. In the real-world, classes are invisible only
objects are visible.
• A class in Java can contain: Fields, Methods, Constructors, Blocks, Nested class and
interface.
• Example: Student
Properties-->name,rollno,height,color-->Fields or variable
Action-->Run(),Read(),Write(),sleep()---> Methods
Objects:
• An object is an instance of a class. An entity that has state and behavior is known as an
object e.g., chair, bike, marker, pen, table, car, Person, Place, bank account, …., so on.
• An object is a physical entity, that entity that has physical existence.
• An object is a runtime entity. The object is an entity which has state and behavior.
• The most important benefits of an objects are Modularity and Reusability.
• The properties of objects are two types visible and invisible.
• Let man is an object, then visible properties are eyes, ears, hands, legs,…so on and
invisible properties are name, blood group,…. so on.
• Every object contains three basic elements Identity (name), State (variables) and
Behavior (methods)
2.2 Class Declaration and Modifiers
Class Declaration:
A class declaration starts with the Access modifier. It is followed by keyword class,
which is followed by the name or identifier. The body of class is enclosed between a pair of
braces { }.
Syntax: Class Identifier
Modifier class Identifier
{
Class Modifier /*Class Members- fields, methods, classes, interfaces */
}
Example:
public class MyFarm
{
double length; //instance variable
double width; //instance variable
}
• Modifiers: A class can be public or has default access (Refer this for details).
• class keyword: class keyword is used to create a class.
• Class Identifier: The name should begin with an initial letter.
• Body: The class body surrounded by braces, { }.
• The class name starts with an upper-case letter, whereas variable names may start win
lower-case letters.
• In the case of names consisting of two or more words as in MyFarm, the other words for
with a capital letter for both classes and variables. In multiword identifiers, there is no
blank space between the words
• Class names should start with an upper-case letter and should be nouns. For example, it
could include names such as vehicles, books, and symbols.
• It should have both upper and lower-case letters with the first letter capitalized.
Class Modifiers:
• Class modifiers are used to control the access to class and its inheritance characteristics.
• Java consists of packages and the packages consist of sub-packages and classes Packages
can also be used to control the accessibility of a class.
• These modifiers can be grouped as
(a) access modifiers→ No modifier, public, private and protected.
(b) non-access modifiers→final and abstract
Examples:
1. A class without modifier.
class Student
{
/* class body*/
}
2. A class with modifier
public class Student
{
/* class body*/
}
2.3 Class Members
The class members are declared in the body of a class. These may comprise fields
(variables in a class). methods, nested classes, and interfaces.
The fields comprise two types of variables
1. Non-Static variables: These include instance and local variables and vanes in scope and
value.
• Instance variables: These variables are individual to an object and an object keeps a
copy of these variables in its memory.
• Local variables: These are local in scope and not accessible outside their scope.
2. Class variables (Static Variables): These variables are also qualified as static 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 belong to the whole class, these are also called class variables.
2.4 Declaration of Class Objects
Creating an object is also referred to as instantiating an object.
• Objects in java are created dynamically using the new operator. The new operator creates
an object of the specified class and returns a reference to that object.
• Syntax: - class-name object-name=new class-name():

Example 1:
class CustomerId
{
static int count=0; // static variable
int id; // instance variable
CustomerId() // Constructor
{
count++;
id = count ;
}
int getId() // Method
{
return id;
}
int localVar()
{
int a=10; //Local variable
return a;
}
}
class Application
{
public static void main(String[] args)
{
CustomerId obj = new CustomerId();
System.out.println("Customer Id = " + obj.getId());
System.out.println("Local Variable = " + obj.localVar());
}
}
Output:
C:\>javac Application.java
C:\>java Application
Customer Id = 1
Local Variable = 10
Example 2:
class Rectangle
{
double l,b; //instance variable
double area()
{
return l*b;
}
public static void main(String args[])
{
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();
//Assign value to rect1 instance variable
rect1.l = 10;
rect1.b = 20;
//Assign value to rect2 instance variable
rect2.l = 30;
rect2.b = 40
System.out.println(“Area of Rectangle1=”+rect1.area());
System.out.println(“Area of Rectangle2=”+rect2.area());
}
}
Output
Area of Rectangle1= 200
Area of Rectangle2= 1200
Note: we can access the members of a class using object name and .(dot) operator
2.5 Constructor Methods
• A constructor is a special method of the class and it is used to initialize an object
whenever the object is created.
• It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
• We can create object with the help of constructor, without constructor object creation is
not possible
Rules for creating Java Constructor
A Constructor is a special method because,
• Class name and Constructor name both must be same
• Doesn’t contain any return type
• Automatically executed when object is created.
Types of Java Constructors
There are two types of constructors in Java:
1. Default Constructor (no-arg constructor)
2. Parameterized Constructor
1. Default Constructor (no-arg constructor)
The Java compiler automatically create a no-arg constructor during the execution of the
program. This constructor is called default constructor.. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the
constructor is empty.
Syntax of default constructor:
<class_name>(){}
Example1 of default constructor that displays the default values
//Let us see another example of default constructor
//which displays the default values
class Student3
{
int id;
String name;
//method to display the value of id and name
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Example2
/* Here, Box uses a constructor to initialize the dimensions of a box. */
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxDemo6
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
2. Parameterized constructor
A constructor which has a specific number of parameters is called a parameterized
constructor. The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Add class that have two parameters.
We can have any number of parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Add
{
int a,b,total;
//creating a parameterized constructor
Add(int x,int y)
{
a=x;
b=y;
}
//method to display the values
void sum()
{
total=a+b;
System.out.println("Sum="+total);
}
}
class Madd
{
public static void main(String args[])
{
//creating objects and passing values
Add obj1=new Add(20,30);
Add obj2=new Add(50,60);
Add obj3=new Add(100,200);
//calling method to display the values of object
obj1.sum();
obj2.sum();
obj3.sum();
}
}
Output
Sum=50
Sum=110
Sum=300
2.6 Constructor Overloading
Constructor overloading means within the same class writing two or more constructor
with same name but different parameters. What are the different parameters?
1. Number of Parameters
Ex: add(int)
add(int,int)
add(int,int,int)
2. Type of Parameter
Ex: add(int,int)
add(double,double)
3. Order of Parameter
Ex: add(int,double)
add(double,int)
Example of Constructor Overloading
/* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
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;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
2.7 Methods Introduction
• A method in Java represents an action on data or behaviour of an object. In other
programming languages, the methods are called functions or procedures.
• A method is a block of code or collection of statements or a set of code grouped together
to perform a certain task or operation.
• It is used to achieve the reusability of code. We write a method once and use it many
times. We do not require to write code again and again.
• It also provides the easy modification and readability of code, just by adding or removing
a chunk of code.
Types of Method
There are two types of methods in Java:
• Predefined Method
• User-defined Method
1. Predefined Method
predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
Example of the predefined method.
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output: - The maximum number is: 9
2. 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.
Types of Methods
• Default Method
• Parametrized Method
2.8 Defining Methods
A method definition comprises two components:
• Header that includes modifier, type, identifier, or name of method and a list of
parameters. The parameter list is placed in a pair of parentheses.
• Body that is placed in braces ({ }) and consists of declarations and executable statement
and other expressions.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
• Public: The method is accessible by all classes when we use public specifier in our
application.
• Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
• Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
• Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
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.
Default Method
Example: -
Adding a Method to the Box Class (Without Return Value)
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// display volume of first box
mybox1.volume();
}
}
Output:- Volume is 3000.0
Adding a Method to the Box Class (Returning a Value)
A Java method may or may not return a value to the function call. We use the return
statement to return any value. For example,
int addNumbers()
{
...
return sum;
}
// Now, volume() returns the volume of a box.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxDemo4
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output
Volume is 3000.0
Volume is 162.0
Parametrized Method
A method parameter is a value accepted by the method. As mentioned earlier, a method
can also have any number of parameters. For example,
// method with two parameters
int addNumbers(int a, int b)
{
// code
}
// method with no parameter
int addNumbers()
{
// code
}
If a method is created with parameters, we need to pass the corresponding values while
calling the method. For example,
// calling the method with two parameters
addNumbers(25, 15);
// calling the method with no parameters
addNumbers()
Example for Method Parameters
class Main
{
// method with no parameter
public void display1()
{
System.out.println("Method without parameter");
}
// method with single parameter
public void display2(int a)
{
System.out.println("Method with a single parameter: " + a);
}
public static void main(String[] args)
{
// create an object of Main
Main obj = new Main();
// calling method with no parameter
obj.display1();
// calling method with the single parameter
obj.display2(24);
}
}
Output
Method without parameter
with a single parameter: 24
2.9 Overloaded Methods
• Method overloading means within the same class writing two or more methods with same
name but different signatures (parameters).
• What are the different parameters?
1. Number of Parameters
Ex: void add(int)
void add(int,int)
void add(int,int,int)
2. Type of Parameter
Ex: int add(int,int)
int add(double,double)
3. Order of Parameter
Ex: double add(int,double)
double add(double,int)
• The compiler executes the version of the method whose parameters match with the
arguments.
• Method overloading is one of the ways that Java supports polymorphism.
Example of Method Overloading
Here is a simple example that illustrates method overloading:
// Demonstrate method overloading.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
2.10 Recursive Methods
• A Method which is calling itself is called as Recursive Method. Recursion in java is a
process in which a method calls itself continuously.
Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}
Example:
class Fact
{
int factorial (int n)
{
if(n<2)
return n;
else
return n*(factorial(n-1));
}
}
class FactDemo
{
public static void main(String[] args)
{
Fact obj =new Fact();
int n=5;
int res = obj.factorial(n);
System.out.println("Factorial of " + n + " = " +res);
}
}
Output:
C:\>javac FactDemo.java
C:\>java FactDemo
Factorial of 5 = 120
2.11 Nesting of Methods
• A method calling in another method with in the class is called as Nesting of Methods.
Example:
class Rectangle
{
void perimeter(int l, int w)
{
System.out.println("Length ="+l+", Width= "+w);
System.out.println("Perimeter = " + (l+w));
}
void area(int l, int w)
{
perimeter(l,w); // Nesting of Method
System.out.println("Area = " + (l*w));
}
}
class RectangleDemo
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.area(5,4);
}
}
Output:
C:\ >javac RectangleDemo.java
C:\ >java RectangleDemo
Length =5, Width= 4
Perimeter = 9
Area = 20
2.12 Nested (Inner) Classes
• Java inner class or nested class is a class that is declared inside the class or interface.
• We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
• A nested class is also a member of its enclosing class. As a member of its enclosing class,
a nested class can be declared private, public, protected, or package private(default).
• Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
• Nested classes are divided into two categories:
1. static nested class : Nested classes that are declared static are called static nested
classes.
2. inner class : An inner class is a non-static nested class.
a. Member inner class
b. Local inner class
c. Anonymous inner class
Static nested class
A static class is a class that is created inside a class, is called a static nested class in
Java. It cannot access non-static data members and methods. It can be accessed by outer class
name.
• It can access static data members of the outer class, including private.
• The static nested class cannot access non-static (instance) data members
Example
class TestOuter1
{
static int data=30;
static class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output
data is 30
Member Inner Class
• A class which is declared within class but outside a method is called Member inner class.
• The inner class has access to all the members of the enveloping class including the
members declared public, protected or private.
Example:
class Outer
{
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}

public void display()


{
Inner in=new Inner();
in.show();
}
}
class Test
{
public static void main(String[] args)
{
Outer ot = new Outer();
ot.display();
}
}
Output:
Inside inner
Local inner class
A local class is declared in a block or a method, and hence, their scope is limited to the
block of method. The general properties of such classes are as follows
• These classes can refer to local variables or parameters, which are declared final
• These are not visible outside the block in which they are declared and hence, the access
modifiers such as public, private, or protected do not apply to local classes.
Example:
class Outer
{
int count;
public void display()
{
for(int i=0;i<5;i++)
{
//Inner class defined inside for loop
class inner
{
public void show()
{
System.out.println("Inside inner "+(count++));
}
}
Inner in=new Inner();
in.show();
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot = new Outer();
ot.display();
}
}
Output
Inside inner 0
Inside inner 1
Inside inner 2
Inside inner 3
Inside inner 4
Anonymous inner class
• Anonymous classes are inner classes without a name.
• It is defined inside another class. Because class has no name it cannot have a constructor
method and its objects cannot be declared outside the class.
• Therefore, an anonymous class must be defined and initialized in a single expression.
• An anonymous class may be used where the class has to be used only once.
• An anonymous class extends a super class or implements an interface, but keywords
extend or implements do not appear in its definition. On the other hand, the names of
super class and interface do appear.
• An anonymous class is defined by operator new followed by class name it extends,
argument
Example:
abstract class Person
{
abstract void display(); //abstract method
}
class AnonymousClass
{
public static void main (String args[])
{
Person obj = new Person()
{ // Creating an object of Anonymous class
void display()
{
System.out.println("In display() method ");
}
}; // anonymous class closes
obj.display(); // Calling anonymous class method
}
}
Output:
C:\>javac AnonymousClass.java
C:\>java AnonymousClass
In display() method
2.13 Final Class and Methods
Final Class
A class that is declared with the final keyword is known as the final class. A final class
can’t be inherited by subclasses. By use of the final class, we can restrict the inheritance of
class. We can create a final class by use of final keyword during the declaration of the class.
Example
final class ParentClass
{
void showData()
{
System.out.println("This is a method of final Parent class");
}
}
//It will throw compilation error
class ChildClass extends ParentClass
{
void showData()
{
System.out.println("This is a method of Child class");
}
}
class MainClass
{
public static void main(String arg[])
{
ParentClass obj = new ChildClass();
obj.showData();
}
}
Output
Main.java:9: error: cannot inherit from final ParentClass
class ChildClass extends ParentClass
^
1 error
Final Method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. In Java, the final method cannot be overridden by the child class.
For example,
class FinalDemo
{
// create a final method
public final void display()
{
System.out.println("This is a final method.");
}
}
class Main extends FinalDemo
{
// try to override final method
public final void display()
{
System.out.println("The final method is overridden.");
}
public static void main(String[] args)
{
Main obj = new Main();
obj.display();
}
}
Output
Main.java:12: error: display() in Main cannot override display() in FinalDemo
public final void display()
^
overridden method is final
1 error
2.14 Keyword this
• The this keyword refers to the current object in a method or constructor.
• The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by
a method or constructor parameter).
• In java, this is a reference variable that refers or identify to the current object.
Usage of java this keyword
Here is given the 3 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
1) this can be used 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.
Understanding the problem without this keyword
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output:
0 null 0.0
0 null 0.0
Solution of the above problem by this keyword
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output:
111 ankit 5000
112 sumit 6000
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.
Let's see the example
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.
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
2.15 Passing Arguments by Value and by Reference
Arguments are the variables which are declared in the method prototype to receive the
values as a input to the Method( Function).
Example:
int add(int a, int b) // method prototype
{
//Body of the method add
return a+b;
}
Here a and b are called as arguments. ( also called as formal arguments)
Arguments are passed to the method from the method calling
Ex:
int x=10,y=20;
add( x , y); // method calling
Here x and y are actual arguments.
Passing Arguments by Value (Call by value)
In call by value actual arguments are copied in to formal arguments.
Example:
class Swap
{
int a,b;
void setValues(int p, int q)
{
a=p;
b=q;
}
void swapping()
{
int temp;
temp =a;
a=b;
b=temp;
}
void display()
{
System.out.println("In Swap Class: a= "+a+" b= "+b);
}
}
class CallByValue
{
public static void main (String args[])
{
int x=10,y=20;
System.out.println("Before Swap : x= "+x+ " y="+y);
Swap obj =new Swap();
obj.setValues(x,y);
obj.swapping();
obj.display();
System.out.println("After Swap : x= "+x+ " y="+y);
}
}
Output:
C:\>javac CallByValue.java
C:\>java CallByValue
Before Swap : x= 10 y=20
In Swap Class: a= 20 b= 10
After Swap : x= 10 y=20
Passing Arguments by Reference (Call by reference)
In call by reference the object will be passed to the method as an argument. At that time
the actual and formal arguments are same. That means any occurs in actual arguments will be
reflected in the formal arguments.
Example:
class Swap
{
int a,b;
void setValues(Swap objSwap)
{
a = objSwap.a;
b = objSwap.b;
}
void swapping()
{
int temp;
temp =a;
a=b;
b=temp;
}
void display()
{
System.out.println("In Swap Class: a= "+a+" b= "+b);
}
}
class CallByReference
{
public static void main (String args[])
{
Swap obj =new Swap();
obj.a=10;
obj.b=20;
System.out.println("Before Swap : obj.a = "+ obj.a+" obj.b="+ obj.b);
obj.setValues(obj); // call by reference
obj.swapping();
obj.display();
System.out.println("After Swap: obj.a = "+ obj.a+ " obj.b="+ obj.b);
}
}
Output:
C:\1. JAVA\PPT Programs>javac CallByReference.java
C:\1. JAVA\PPT Programs>java CallByReference
Before Swap : obj.a = 10 obj.b=20
In Swap Class: a= 20 b= 10
After Swap : obj.a = 20 obj.b=10

You might also like