You are on page 1of 21

UNIT – II

FUNDAMENTALS OF OBJECT ORIENTED PROGRAMMING

Introduction
The invention of the computer, many programming techniques have been tried such as modular
programming, top-down programming, bottom-up programming and structured programming. The
objectives of these techniques to handle the increasing complexity of programs are reliable and
maintainable. Structured programming, like C became very popular and was the paradigm of the 1980s.
The structured approach failed to show the desired results in terms of bug-free, easy-to-maintain and
reusable programs. Object-Oriented programming is an approach to program organization and
development, which attempts to eliminate some of the pitfalls of conventional programming methods
by incorporating the best of structured programming features with several new concepts. C++ is a
procedural language with object-oriented extension, but Java, a pure object oriented language.

Object Oriented Paradigm

The objective of object-oriented approach is to eliminate some of the flaw encountered in the
procedural approach. OOP allows us to decompose a problem into a number of entities called objects
and then build data and functions around these entities. The organization of data and methods in object
as shown in the fig. 1.3.2.a.

Method Method

Dat

Method Method

Fig.1.3.2.a Object = Data + Methods

The data of an object can be accessed by methods associated with object andmethod of one object can be
access the methods of other object.
Features of object-oriented paradigm are:
 Emphasis is on data rather than procedure.
 Programs are divided into objects.
 Data structures are designed.
 Methods that operate on the data of an object are tied together in the data structure.
 Data hidden and cannot be accessed by external functions.
 Objects may communicate with each other through methods.
 New data and methods can be added easily.
 Employs bottom-up approach in program design.
Object-oriented programming is an approach that provides a way of modularizing
programs by creating partitioned memory area for both data and function that can be used as
templates for creating copies of such modules on demand.

1
Basic Concepts of OOPS
The basic concepts of OOPS, which form the heart of Java language as follow as:
1. Objects
Objects are basic runtime entities in an object-oriented system. They may represent person, a
place, a table of data or any data item that the program must handle.
They may also represent user-defined data types such as vectors and lists. Objects take up space in the
memory and have an associated address like a structure in C.
When a program is executed, the object interacts by sending messages to one another. For
example ‘customer’ and ’account’ are two objects in a banking system, then the customer object send a
message to the account object requesting for balance. Each object has data and code to manipulate the
data. Fig. 1.3.3.a shows a notation to represent an object.

OBJECT: Student
DATA: Name
Reg.No.
Marks

METHODS: Total
Average
Fig.1.3.3.a Representation of an object
2.Classes
The entire set of data and code of an object can be made a user defined data type with the help of a
class. In fact, objects are variables of type class. Once a class has been defined, we can create any number of
objects based on that class. A class has collection of objects of similar type. For example circle, square,
rectangle and ellipse are members of the class shape.

3.Data Abstraction and Encapsulation


The wrapping up of data and methods into single unit is called encapsulation. The data is not accessible to
the outside world and only those methods are wrapped in the class can access it. These methods provide the
interface between object’s data and the program. This insulation of the data from direct access by the
program is called data hiding.
Abstraction refers to representing features without the background details. Classes use the concept
of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and methods that
operate on these attributes.

4.Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
For example, the B.C.A., (Computer Applications) is a part of the class Department Computer science,
which is again a part of the class College. Inheritance properties are as shown in Fig.1.3.3.b. In OOP, the
concept of inheritance provides the idea of reusability. We can add additional features to an existing
classwithout modifying it.

2
College

Attributes:

Computer
Science Dept.
Computer
Attributes: Applications Dept.
------------
Attributes:
------------

B.Sc(CS) M.Sc(CS)

Attributes: Attributes:
------------ ------------ B.C.A M.C.A

Attributes: Attributes:

Fig.1.3.3.b Property Inheritance


5.Polymorphism

Polymorphism is the ability to take more than one form. An operation may
exhibit different behavior in different instances. The behavior depends upon the data
types of data used in the operation. For example, consider the operation of addition with
two numbers will generate summation and with two String would produce a third string by
concatenation. Fig. 1.3.3.c that shows
the single method name can be used to handle different number and different types ofarguments.
Addition

Add()

Summation Concatenation
Add(Integer) Add(String)

Fig.1.3.3.c Polymorphism

6.Dynamic Binding
Binding refers to linking of a procedure call to the code executed in response tothe call.
Dynamic binding means that the code associated with a given procedure call is not known until the
time of the call at runtime.

7.Message communication
An Object-oriented program consists of set objects that communicate with each other. The
process of programming in an object-oriented language, involves the following basic

3
steps:
 Creating classes that define objects and behavior.
 Creating objects from class definitions.
 Establishing communication among object.
Objects communicate with one another by sending and receiving information as shown inFig.1.3.3.d.
Object

Object Object

Object Object

Fig.1.3.3.d Network of objects communicating between them


A message for an object is a request for execution of a procedure, and will invokes a
method in the receiving object that generates desired result, as shown in Fig.1.3.3.e

Sending Object Method() Receiving object


Message

Fig.1.3.3.e Message triggers a method


Message passing involves specifying name of the object, the name of the method(message) and
information to be sent.
Example:

Student.averageMarks (Reg.No)

 Benefits Of OOP
OOP offers several benefits to both the program designer and the user.
 Through inheritance, we can eliminate redundant code and extend the use exiting classes.
 We can build programs from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch. This leads to saving of development time
and higher productivity.
 It is possible to have multiple objects to coexist without any interference.
 It is possible to map objects in the problem domain to those objects in the program
 It is easy to partition the work in a project based on objects.
 The data-centered design approach enables us to capture more details of a model in an
implementable form
 Object-oriented systems can be easily upgraded from small to large systems.
 Message passing techniques for communication between objects make the interfacedescription
with external systems much simpler.
 Software complexity can be easily managed.

4
Applications Of OOP
The promising areas for application of OOP include:

 Real-time systems
 Simulation and modeling
 Object-oriented databases
 Hypertext, hypermedia and expert text
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAD/CAM System

5
CONSTRUCTOR

In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: 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.

Rules for creating Java constructor


There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:

<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object
creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output
Bike is created

6
Java 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 Student 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 Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor

7
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
A constructor is used to initialize the state of an object. A method is used to expose the behavior of
an object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor if you The method is not provided by the compiler
don't have any constructor in a class. in any case.
The constructor name must be same as the class name. The method name may or may not be same
as the class name.

8
Finalizer

finalize() method in Java is a method of the Object class that is used to perform cleanup activity
before destroying any object. It is called by Garbage collector before destroying the objects from memory.
finalize() method is called by default for every object before its deletion. This method helps Garbage
Collector to close all the resources used by the object and helps JVM in-memory optimization.

finalize() method in Java is used to release all the resources used by the object before it is
deleted/destroyed by the Garbage collector. finalize is not a reserved keyword, it's a method. Once the clean-
up activity is done by the finalize() method, garbage collector immediately destroys the Java object. Java
Virtual Machine(JVM) permits invoking of finalize() method only once per object. Once object is finalized
JVM sets a flag in the object header to say that it has been finalized, and won't finalize it again. If user tries
to use finalize() method for the same object twice, JVM ignores it.

Visibility Modifiers Or Access Modifiers In Java


Access modifiers are object-oriented programming that is used to set the accessibility of
classes, constructors, methods, and other members of Java.

Using the access modifiers we can set the scope or accessibility of these classes, methods,
constructors, and other members.
JAVA has two types of modifiers: access modifiers and non-access modifiers.
What are Access Modifiers?

Access modifiers are keywords that can be used to control the visibility of fields, methods, and constructors
in a class. The four access modifiers in Java are public, protected, default, and private.

Four Types of Access Modifiers

 Private: We can access the private modifier only within the same class and not from outside the
class. 

 Default: We can access the default modifier only within the same package and not from outside the
package. And also, if we do not specify any access modifier it will automatically consider it as
default.

 Protected: We can access the protected modifier within the same package and also from outside the
package with the help of the child class. If we do not make the child class, we cannot access it from
outside the package. So inheritance is a must for accessing it from outside the package.

 Public: We can access the public modifier from anywhere. We can access public modifiers from
within the class as well as from outside the class and also within the package and outside the
package.

9
Let us see which all members of Java can be assigned with the access modifiers:

Members of JAVA Private Default Protected Public


Class No Yes No Yes
Variable Yes Yes Yes Yes
Method Yes Yes Yes Yes
Constructor Yes Yes Yes Yes
interface No Yes No Yes
Initializer Block NOT ALLOWED

Now let us understand the scope of these access modifiers with the help of a table:

Accessibility Private Default Protected Public


Same Package Same Class Yes Yes Yes Yes
Without Inheritance No Yes Yes Yes
With Inheritance No Yes Yes Yes
Different Package Without Inheritance No No No Yes
With Inheritance No No Yes Yes
Let’s understand with more details:

Private Access Modifier


 The private access modifier is specified when any member of a class is prefixed with the private
keyword. In comparison with the other access modifiers, this is the most restricted access modifier.

 When the methods or data members are prefixed with a private access modifier, the visibility of these
methods and data members are restricted so, they can be accessed only within the same class where
they have been declared, they will not be visible to the outside world.

 If we have another class from the same package still, we will not be able to access these methods or data
members. So usually, we keep the class variables and methods as private, which are intended to be used
inside the same class where declared.

Default Access Modifier


 It is not a keyword. Any Java members such as class or methods or data members when not specified
with any access modifier they are by default considered as default access modifiers. These methods or
data members are only accessible within the same package and they cannot be accessed from outside
the package. It provides more visibility than a private access modifier. But this access modifier is more
restricted than protected and public access modifiers.

Protected Access Modifier


 It is a keyword. This access modifier is used to access the methods or data members of a class within the
same package as well as outside the package but only through inheritance. The protected access
modifier has more accessibility than private and defaults access modifiers. But it has less visibility than
the public access modifier.

10
Public Access Modifier
 It is a keyword. If a class member like variable, method, or data members are prefixed with a public
access modifier, then they can be accessed from anywhere inside the program. That is, they can be
accessed within the same class as well as from outside the different classes.

 It also includes access within the same package and also from outside the package. The members like
variables, methods, and other data members can be accessed globally.

 Using public access modifiers we can provide access to the members most simply. There are no
restrictions on public access modifier members. Hence, it has the widest accessibility or visibility
scope as compared to the rest of the access modifiers.

 
Access within within outsidepackagebysubclass outside
Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y


11
OBJECTS AND CLASSES IN JAVA
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity
only.

What is an object in Java?


An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car,
etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking
system.
OR
An object is called 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, etc. Creating an object is also referred to as instantiating an object.
Object in Java created using new operators.
An object has three characteristics:
o State: represents the data (value) of an object.
o Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so
writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class
o
What is a class in Java?
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>
{
field;
method;
}

12
EX: class Rectangle
{
int length;
int width;
voidgetData(intx,inty)
{
length=x;
width=y;
}
}
Creating an Object in Java
This is the most popular way to create an object in Java. A new operator is also followed by a call to
constructor which initializes the new object. While we create an object it occupies space in the heap.

Syntax
class_name object_name = new class_name()

Example: Rectanglerect1;//declare
rect1=newRectangle();//instantiate

Method Declaration
A class with only data fields has no life. Methods are declared inside the body of the
class but immediately after the declaration of instance variables.
The general form of a method declaration is
Type methodname(parameter-list)
{
method-body;
}

Method declarations have four basic parts:


 The name of the method(method name)is a valid identifier.
 The type of the value the method returns (type). This could be simple data type such as
int as well as any type. It could even be void type, if the method does not return any
value.
 A list of parameters (parameter-list) is always enclosed in parentheses. This list
contains variable names and types of all values we want to give to the method as input.
Example:
(int m, float a, float b) //Three parameters
() Empty list
 The body of the method actually describes the operations to be performed on the data.
Example: class Rectangle
{
intlength;
int width;
voidgetData(intx,inty)
{
length=x;
width=y;
}}

13
INBUILT CLASSES LIKE STRING

The string represents a sequence of characters in Java by using a character array. The
java.lang.String class is used to create a string object.
Example:
char chararray[ ] =newchar[3];
chararray[ ]= ‘H’;
chararray[ ]=‘a’;
chararray []=‘i’;

In Java strings are class objects and implanted using two classes, namely
String and StringBuffer. A Java string is an instantiated object of the String class.

Strings may be declared and createdas


String stringName;
String Name=new String(“string”);

EX: String firstName;


firstName=new String(“Harshinni”);

The String class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable
strings. Because String objects are immutable they can be shared. For example:

String str = "abc"; is equivalent to:


char data[] = {'a', 'b', 'c'};
String str = new String(data);

Here are some more examples of how strings can be used:


System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

The class String includes methods for examining individual characters of the sequence, for
comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all
characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version
specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for
conversion of other objects to strings. String concatenation is implemented through
the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through
the method toString, defined by Object and inherited by all classes in Java. For additional information on
string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

14
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause
a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented
by surrogate pairs (see the section Unicode Character Representations in the Character class for more
information). Index values refer to char code units, so a supplementary character uses two positions in
a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to
those for dealing with Unicode code units (i.e., char values).

15
STRINGBUFFER CLASS
StringBuffer is a peer class of String that provides much of the functionality of strings. The string
represents fixed-length, immutable character sequences while StringBuffer represents growable and
writable character sequences. StringBuffer may have characters and substrings inserted in the middle or
appended to the end. It will automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.

StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.

Important Constructors of StringBuffer class


 StringBuffer(): creates an empty string buffer with the initial capacity of 16.
 StringBuffer(String str): creates a string buffer with the specified string.
 StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.

1) append() method
The append() method concatenates the given argument with this string.

2) insert() method
The insert() method inserts the given string with this string at the given position.
3) replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex-1.

4) delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex-1.
5) reverse() method
The reverse() method of StringBuilder class reverses the current string.

6) capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases
the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.

Constructors of StringBuffer class


1. StringBuffer(): It reserves room for 16 characters without reallocation
StringBuffer s = new StringBuffer();

2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the buffer.
StringBuffer s = new StringBuffer(20);

3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without reallocation.
StringBuffer s = new StringBuffer("GeeksforGeeks");

16
Methods of StringBuffer class
Methods Action Performed
append() Used to add text at the end of the existing text.
length() The length of a StringBuffer can be found by the length( ) method
capacity() the total allocated capacity can be found by the capacity( ) method
charAt() This method returns the char value in this sequence at the specified index.
delete() Deletes a sequence of characters from the invoking object
deleteCharAt() Deletes the character at the index specified by loc
ensureCapacity() Ensures capacity is at least equals to the given minimum.
insert() Inserts text at the specified index position
length() Returns length of the string
reverse() Reverse the characters within a StringBuffer object
replace() Replace one set of characters with another set inside a StringBuffer object
Note: Besides that, all the methods that are used in the String class can also be used. These auxiliary

17
JAVA FILES
In Java, a File is an abstract data type. A named location used to store related information is known
as a File. There are several File Operations like creating a new File, getting information about File,
writing into a File, reading from a File and deleting a File.

Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.
Stream:
A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.

Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a process in
which an input is provided and executed with the byte data.

Character Stream
Character Stream is mainly involved with character data. A file handling process with a character stream is
a process in which an input is provided and executed with the character data.

Java File Class Methods


S.No. Method Return Description
Type
canRead() Boolean The canRead() method is used to check whether
1.
we can read the data of the file or not.
createNewFile() Boolean The createNewFile() method is used to create a
2.
new empty file.
canWrite() Boolean The canWrite() method is used to check whether
3.
we can write the data into the file or not.
exists() Boolean The exists() method is used to check whether the
4.
specified file is present or not.
5. delete() Boolean The delete() method is used to delete a file.
getName() String The getName() method is used to find the file
6.
name.
getAbsolutePath() String The getAbsolutePath() method is used to get the
7.
absolute pathname of the file.
length() Long The length() method is used to get the size of the
8.
file in bytes.

18
list() String[] The list() method is used to get an array of the
9.
files available in the directory.
mkdir() Boolean The mkdir() method is used for creating a new
10.
directory.

File Operations

We can perform the following operation on a file:


o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File

Create a File
Create a File operation is performed to create a new file. We use the createNewFile() method of file.
The createNewFile() method returns true when it successfully creates a new file and returns false when the
file already exists.

Get File Information


The operation is performed to get the file information. We use several methods to get the information about
the file like name, absolute path, is readable, is writable and length.

Write to a File
The next operation which we can perform on a file is "writing into a file". In order to write data into a file,
we will use the FileWriter class and its write() method together. We need to close the stream using
the close() method to retrieve the allocated resources.

Read from a File


The next operation which we can perform on a file is "read from a file". In order to write data into a file,
we will use the Scanner class. Here, we need to close the stream using the close() method. We will create an
instance of the Scanner class and use the hasNextLine() method nextLine() method to get data from the
file.

Delete a File
The next operation which we can perform on a file is "deleting a file". In order to delete a file, we will use
the delete() method of the file. We don't need to close the stream using the close() method because for
deleting a file, we neither use the FileWriter class nor the Scanner class.

19
THIS KEYWORD IN JAVA

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object.

Usage of Java this keyword


Here is given the 6 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.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

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.

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.

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.

Real usage of this() constructor call


The this() constructor call should be used to reuse the constructor from the constructor. It maintains the
chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that
displays the actual use of this keyword.

4) this: to pass as an argument in the method


The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling.

5) this: to pass as argument in the constructor call


We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes.

20
6) this keyword can be used to return current class instance
We can return this keyword as an statement from the method. In such case, return type of the method
must be the class type (non-primitive).

21

You might also like