OOP Java Module 1 - 09022023

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Module 1

Contents:
Object Oriented Programming (OOP) – Characteristics of OOP – Features of JAVA –
Advantages of JAVA – Tools Available of JAVA Programming (JDK, JAVA Packages, various IDEs
like NetBeans, eclipse) – Building Java applications.
Objects and Classes – Defining a Class – Declaring attributes, Declaring and Defining
methods, Creating Object – Accessing Objects - Constructors – Constructor overloading – Static
variables, constants and methods – method overloading – Visibility modifiers, Data field
Encapsulation, passing and returning objects as arguments, Array of objects-Exception handling,
Try,catch,-Multiple catch & finally statement.

Courtesy:
Balagurusamy E: “Programming with Java”, 3e/5e, and some web resources.

OBJECT ORIENTED PARADIGM:


Some features of this paradigm are;
● Emphasis is on data rate than procedure.
● Programs are divided into entities called objects.
● Data structures are designed to characterize the objects.
● Methods that operate on the data of an object are tied together in the data structure.
● Data is hidden and cannot be accessed by external functions.
● Objects may communicate with each other through methods.
● New data and methods can be easily added whenever necessary.
● Following bottom-up approach in program design. (In this design, individual parts of
the system are specified in detail. The parts are linked to form larger components,
which are in turn linked until a complete system is formed)

What is Object Oriented Programming (OOP)?


OOP is an approach that provides a way of modularizing programs by creating partitioned
memory areas for both data and functions that can be used as templates for creating copies of such
modules on demand. An object is considered to be a partitioned area of computer memory that stores
data and a set of operations that can access the data.

CHARACTERISTICS OF OOP (CONCEPTS OF OOP):


The general concepts of OOP that forms the heart of Java language are;

Objects and Classes:


Objects are the basic runtime entities in an object-oriented system. They may represent a
person, a place, a table of data, a bank account etc. They can also be lists or vectors. The objects
should be chosen such that they match closely with the real world objects. When a program is
executed, the objects may interact by sending messages to one another, for example, ‘customer’ object
requests to ‘account’ object for account balance in a banking program. Each object has some data and
methods to manipulate that data. The blueprint or prototype of an object is called a class. A class is a
template for creating objects in a program, whereas the object is an instance of a class. A class is a
logical entity, while an object is a physical entity. A class does not allocate memory space; on the other

S4 CT/CHE - OOP Java - Module 1 Page 1 of 25


hand, an object allocates memory space. In the real-world, if fruit is a class, then mango, orange and
apple are objects.

Representation of an Object

Data Abstraction and Encapsulation:


The wrapping up of data and methods into a single unit (called class) is known as
encapsulation. The data is not accessible to the outside world. Only the methods inside the same class
can access it. These methods provide the interface between the object’s data and the program. This
insulation of the data from direct access by the program is called data hiding. Encapsulation helps the
objects to be treated as black boxes, each performing a specific task without revealing the internal
implementation. Abstraction refers to the act of representing essential features without including the
background detail or explanations.

Inheritance:
Inheritance is the process by which an object of one class acquires the properties of objects of
another class. Inheritance supports the concept of hierarchical classification. For example, the bird
Robin is a part of the class Flying Bird, which is again the part of the class Bird. The principle behind
the inheritance is that each derived class shares common characteristics with the class from which it is
derived. Inheritance helps for code reusability also. This means that, after deriving a new class from an
existing one, we can add additional features to the new one, without modifying the old one. Thus the
new class will have combined features of both the classes. The new class is called a subclass.

Polymorphism:
Polymorphism means the ability to take more than one form. For example, an operation may
exhibit different behavior in different situations. The behavior depends upon the type of data used in
the operation. For example, the operator for addition performs simple addition if the operands are
integers and does the concatenation if the operands are strings.

Dynamic Binding:
Binding refers to the linking of a function call to the code. Dynamic binding means that the
code associated with a given procedure call is not known until the time of the call at runtime. It is
associated with polymorphism and inheritance. For example, if there is a function ‘sum’ with two and
three parameters, the proper function will be selected only when the call is made.

S4 CT/CHE - OOP Java - Module 1 Page 2 of 25


Message Communication:
An object-oriented program consists of a set of objects that communicate with each other. The
process of the programming therefore involves three steps.
1. Creating the classes that define objects and their behavior.
2. Creating the objects from class definitions.
3. Establishing communications among them.
The communication happens through message passing. A message of an object is normally a
request for execution of a procedure, and hence will invoke a method in the receiving object that
generates the desired result. Message passing involves specifying the name of the object, the name of
the method (message) and the information to be sent. For example, in Employee.getSalary(name).
Here Employee is the object, getSalary is the message and name is the parameter that contains
information.

HISTORY OF JAVA:
Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of the USA in 1991. Its original name was Oak. It was designed for the development of
software for consumer electronics like TVs. Java is the first programming language that is not tied to
any particular hardware or operating system. Thus Java is a Platform-neutral or Platform-independent
language.

FEATURES OF JAVA:
● Compiled and Interpreted
● Platform-Independent and Portable
● Object-Oriented
● Robust and Secure
● Distributed
● Familiar, Simple and Small
● Multithreaded and Interactive
● High Performance
● Dynamic and Extensible
● Ease of Development
● Scalability and Performance

Compiled and Interpreted:


First, the Java compiler translates the source code into a type of code called Bytecode. In the
second stage, the Java interpreter generates machine code that can be directly executed by the machine
that is running the Java program. Thus we can say that Java is both a compiled and an interpreted
language.

Platform-Independent and Portable:


Portability is the major feature of Java. Java programs can be easily moved from one computer
system to another, anywhere and any time. Changes and upgrades in the operating systems, processors
and system resources will not force any change in Java programs. Thus Java programs can be executed
over the internet also and such programs are called applets.

S4 CT/CHE - OOP Java - Module 1 Page 3 of 25


Object-oriented:
Java is a true object-oriented language. All program code and data reside within objects and
classes. Java has an extensive set of classes, arranged in packages, that we can use in our programs by
inheritance.

Robust and secure:


Java has strict compile time and run time checking for data types to ensure the reliability of
code. Java has a garbage collector to deallocate the memory of objects and variables that are
exhausted. Java does not have pointers and hence avoids unauthorized memory access. This improves
security.

Distributed:
Java is designed as a distributed language for creating applications on the network. It has the
ability to share both data and programs. Java applications can open and access remote objects on the
Internet as easily as they can do in a local system. This enables multiple programmers at multiple
remote locations to collaborate and work together on a single project.

Simple, small and familiar:


Java is simple and small as it does not have preprocessor header files, pointers, goto
statements, operator overloading, multiple inheritance and many more features which might have
increased the complexity. Anyone who is familiar with C or C++ can easily follow the Java programs.

Multithreaded and Interactive:


Java supports multithreading and hence it can handle multiple tasks simultaneously. This in
turn helps to execute interactive programs at the same time.

High Performance:
With the help of bytecode, the Java speed is comparable to C and C++.

Dynamic and Extensible:


Java is capable of dynamically linking in new class libraries, methods and objects. Java
programs support functions written in other languages such as C and C++. These functions are known
as native methods. This facility enables programmers to use the efficient functions available in these
languages. Native methods are linked dynamically at runtime.

Ease of Development:
The object and class concepts help in code reusing. Other features in Java such as inheritance,
polymorphism also helps to reuse code and hence helps in easy development of applications.

ADVANTAGES OF JAVA:

1. Simple
Java is a simple programming language since it is easy to learn and easy to understand. Its
syntax is based on C++, and it uses automatic garbage collection; therefore, we don't need to remove

S4 CT/CHE - OOP Java - Module 1 Page 4 of 25


the unreferenced objects from memory. Java has also removed the features like explicit pointers,
operator overloading, etc., making it easy to read and write.

2. Object-Oriented
Java uses an object-oriented paradigm, which makes it more practical. Everything in Java is an
object which takes care of both data and behavior. Java uses object-oriented concepts like object,
class, inheritance, encapsulation, polymorphism, and abstraction.

3. Secured
Java is a secured programming language because it doesn't use explicit pointers. Also, Java
programs run inside the virtual machine sandbox.

4. Robust
Java is a robust programming language since it uses strong memory management. We can also
handle exceptions through the Java code. Also, we can use type checking to make our code more
secure. It doesn't provide explicit pointers so that the programmer cannot access the memory directly
from the code.

5. Platform independent
Java code can run on multiple platforms directly, I.e., we need not compile it every time. It is a
Write Once, Run Anywhere language (WORA) which can be converted into byte code at the compile
time. The byte code is a platform-independent code that can run on multiple platforms.

6. Multi-Threaded
Java uses a multi-threaded environment in which a bigger task can be converted into various
threads and run separately. The main advantage of multi-threading is that we need not provide memory
to every running thread.

TOOLS AVAILABLE OF JAVA PROGRAMMING


The Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools are part of the system known as Java Development Kit (JDK).
The classes and methods are part of the Java Standard Library (JSL), also known as Application
Programming Interface (API).

The Java Development Kit contains tools for developing and running Java programs. They are;
● Javac (Java compiler)
● Java (Java interpreter)
● Appletviewer (for viewing Java applets)
● Javap (Java disassembler)
● Javah (for C header files)
● Javadoc (for creating HTML documents)
● Jdb (Java debugger)

S4 CT/CHE - OOP Java - Module 1 Page 5 of 25


The Application Programming Interface (API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are;
● Language Support Package: Required for implementing basic features of Java.
● Utilities Package: To provide utility functions such as date and time functions.
● Input/Output Package: Required for input/output manipulations.
● Networking Package: For communicating with other computers via the Internet.
● AWT Package: The Abstract Window Toolkit package contains classes that implement
platform-independent graphical user interface.
● Applet Package: To create Java applets.

Java Virtual Machine (JVM): The java program when compiled gives a special type of code called the
bytecode. The code is run on a virtual machine in the host operating system. This virtual machine is
called the Java Virtual Machine (JVM). It exists only in the computer memory. The JVM is the engine
that provides a runtime environment to drive the Java Code or applications. It converts Java bytecode
into machine language. JVM is a part of Java Runtime Environment (JRE). It is responsible for the
portability of the Java applications.

BUILDING JAVA APPLICATIONS


To create a Java program, we need to create a source code file using a text editor. Even though
any text editor can be used for writing the code, most programmers use Java IDEs which help them for
faster and error free coding, debugging and execution. A Java IDE (Integrated Development
Environment) is a software application that enables users to write and debug Java programs more
easily. Most IDEs have features such as syntax highlighting and code completion that helps users to
code more easily. Usually, Java IDEs include a code editor, a compiler, a debugger, and an interpreter
that the developer may access via a single graphical user interface. Some common IDEs are Eclipse,
NetBeans, JCreator, BlueJ, etc.
The source code is then compiled using the java compiler javac and executed using the Java
interpreter java. The java debugger jdb is used to find errors, if any, in the source code. A compiled
java program can be converted into a source code with the help of Java disassembler javap.
In a nutshell, the implementation of a Java application program involves major three steps;
● Creating the program
● Compiling the program (javac filename.java)
● Running the program (java mainClassName)

The process of building and running a Java application program is given in the figure below.

S4 CT/CHE - OOP Java - Module 1 Page 6 of 25


S4 CT/CHE - OOP Java - Module 1 Page 7 of 25
JAVA PROGRAMMING - OBJECTS AND CLASSES

SAMPLE JAVA PROGRAM


The program given below will print Hello World on the execution terminal.
class HelloWorld
{
public static void main(String args[ ])
{
System.out.println("Hello World");
}
}

Explanation of the program:


● Class Declaration: Class HelloWorld
It declares a class named HelloWorld. Class is an object-oriented concept. As java is a true
object-oriented language, everything will be inside a class. Hence at least one class will be
there in a program. The word class is the keyword to specify the class and HelloWorld
specifies the name of the class. The class declaration should be followed by the class definition
block, opened and closed by braces.
● public static void main(String args[ ])
This line defines a method named main, similar to main() function in C and C++. Every Java
application should have a class with a main function. There can be only one main function in
an application. The execution starts from the main function. The keyword public is an access
specifier that makes the main function accessible to all other classes. The keyword static
declares the main method as one that belongs to the entire class and not a part of any objects of
the class. The keyword void states that the main method does not return any value. The main
function has a formal parameter args which is an array of String class objects, received
generally from command line.
● System.out.println(“Hello World”);
This is similar to the printf() function in C and cout<< in C++. Since Java is a true
object-oriented language, every method must be part of an object. The println method is a
member of the out object, which is a static data member of the System class. The line prints
Hello World on the screen. Every statement must end with a semicolon just like C/C++.

Java Program Structure


● The documentation section is a set of comment lines showing the name of the program, the
author details, the purpose of the program, classes etc. It improves the maintenance of the
program.
● The Package statement declares a package name and informs the compiler that the classes
defined here belong to this package. If we do not need to include the classes into packages, we
can avoid this line.
● Import statements are just like #include in C. There can be one or more such statements. These
are used to include the classes of some other packages into our program.
○ Eg: import Student.test; includes the test class of Student package into our program.
● Interface statements are needed when we use multiple inheritance. These are just like
method/function declarations.
S4 CT/CHE - OOP Java - Module 1 Page 8 of 25
● Class definitions define all the classes that are part of the program other than the main class.
Small programs may not have these additional classes and there may be only the main class.
● Main Method Class: As the java program execution starts with the main method, there should
be at least one class which contains the main method.

Sample Java Program 2: Two classes


class Room // class 1
{
float length;
float breadth;

void setData(float a, float b)


{
length=a;
breadth=b;
}

void printDetails()
{
System.out.println("Room length: " + length);
System.out.println("Room breadth: " + breadth);
System.out.println("Room area: " + (length*breadth));
}
}

class RoomInfo // class 2, main method class


{
public static void main(String args[ ])
{
Room livingRoom = new Room();
livingRoom.setData(8,6);
System.out.println("Room Details:");
livingRoom.printDetails();
}
}

S4 CT/CHE - OOP Java - Module 1 Page 9 of 25


The above program will give the following output.
Room Details:
Room length: 8.0
Room breadth: 6.0
Room area: 48.0

Defining a Class:
As Java is a true object-oriented language, all the codes must be inside one or more classes.
Classes are user-defined data types. Classes provide a convenient method for packing together a group
of logically related data items and functions that work on them. In Java the data items are called fields
or attributes and the functions are called methods. The class is a template description of how to make
an object that contains fields and methods. There will not be any semicolon at the end of the class
definition.
Syntax to define a class (everything in square brackets is optional):
class classname [extends superclassname]
{
[ fields declaration; ]
[ methods declaration; ]
}
The keyword extends indicates that the classname class inherits the properties from a parent class
superclassname.
Example for class:
class Room
{
float length;
float breadth;

void setData(float a, float b)


{
length=a;
breadth=b;
}

void printDetails()
{
System.out.println("Room length: " + length);
System.out.println("Room breadth: " + breadth);
System.out.println("Room area: " + (length*breadth));
}
}

Declaring Field/Attribute:
The data is encapsulated in a class by placing the data fields inside the body of the class
definition. These variables are called instance variables or member variables. Their declaration is very
much similar to local variable declaration. Their types can be any standard type or user-defined type
(including other class types). As these variables are only declared and not assigned any values, the
instance variables will not consume any storage space.
Eg:
class Room
{

S4 CT/CHE - OOP Java - Module 1 Page 10 of 25


float length;
float breadth;
}

Here the Room class contains two floating point variables length and breadth.

Declaring and Defining Methods:


The actions that are performed inside a class are refined as methods. The member variables in
a class are not desired to be accessed directly from outside, but through proper methods inside the
class. Also the objects created by the class can communicate with other objects only through messages
which are in turn specified as methods inside the class. Thus the class must have;
● methods that are necessary for manipulating the data inside the class.
● methods to communicate with the outside of the class.
These methods are declared/defined inside the class just after the field declaration. The method
declaration/definition is similar to that of C/C++ functions.
Syntax:
access-specifier return-type methodname (parameter-list)
{
method-body;
}

The method declaration/definition has the following parts;


1. Access-specifier: It can be default, public, private or protected. If nothing is specified, they are
treated as default, and can be accessed from anywhere inside the package.
2. The type of the value the method returns (return-type): It may have a primitive data type,
object, void, etc. If the method does not return anything, we use the void keyword.
3. The name of the method (methodname): The name should specify the purpose of the method.
4. 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, leave
the parentheses blank.
5. The body of the method (method-body).

Creating Objects:
When we create the variables of a class, those variables are known as objects. A class is a
logical entity, and hence does not require memory. But an object is a physical entity and hence
requires memory to exist. Creating an object is also called instantiating an object. An object of a class
is also called an instance of the class.
An object can be just declared or instantiated. Declaring an object can be done by typing
classname objectname. The object can be used only when it is instantiated. Objects are instantiated (or
created) using the new operator.
Eg: Room livingRoom; // Declaring the object livingRoom
livingRoom = new Room(); // Instantiation. Returning a reference
// of the created object to the variable ‘livingRoom’.

This can be simple written into one line as


Room livingRoom = new Room();

S4 CT/CHE - OOP Java - Module 1 Page 11 of 25


The method Room( ) is called the default constructor of the class Room. We can create many objects
of the same class. Also we can create many references to the same object.

Accessing Class Members:


The members (attributes or methods) can be accessed only after the object is instantiated. After
the instantiation, the members can be accessed using the dot operator.
Syntax:
objectname.variablename = value;
objectname.methodname(parameter-list);
Eg: livingRoom.length=4.0; // not common
livingRoom.breadth=3.0;

livingRoom.setData(5.2,3.0);
livingRoom.printDetails( );

CONSTRUCTORS
While creating an object, it is possible to give initial values to objects using two approaches.
The first one is by using dot operators followed by attribute names. For example c.radius=2.0. The
second one is by calling specific methods and putting the causes as formal parameters. For example,
c.setRadius(2.0).
Apart from this, it is possible to assign initial values to the objects during their creation time.
This is using a special type method known as constructor. With the help of the constructor an object
can initialize itself. The features of constructor are;
● Constructors have the same name as the class itself.
● They do not have a return type or return value, not even void.
● They cannot be called using dot operators.
Eg:
class Rectangle
{
int length, width;

Rectangle(int x, int y) // constructor


{
length=x;
width=y;
}

int rectArea()
{
return (length*width);
}
public static void main(String[] args)
{
Rectangle rect1 = new Rectangle(15,10);
int area = rect1.rectArea();
System.out.println("Area="+area);
}
}

S4 CT/CHE - OOP Java - Module 1 Page 12 of 25


The line Rectangle rect1 = new Rectangle(15,10); will create a new object along with explicitly
calling the constructor method by itself. This constructor is called a parameterized constructor as it
has formal parameters passed to it. A constructor without formal parameters is called a default
constructor. We can either define a default constructor as Rectangle() with a method body which
contains the statements to be executed during normal object creation. If we don’t create such a
constructor the system will internally create it and call it without a body and the attribute variables will
be assigned their default initial values.
Eg:
Rectangle() // default constructor created by the programmer
{
length=0;
width=0;
}

Default constructor created by the System defines the Default constructor


programmer

class Rectangle class Rectangle


{ {
int length, width; int length, width;

int rectArea()
Rectangle() {
{ return (length*width);
length=1; }
width=1;
} public static void main(String[] args)
{
Rectangle rect1 = new Rectangle();
int rectArea()
int area = rect1.rectArea();
{ System.out.println("Area="+area);
return (length*width); }
} }

public static void main(String[] args)


{
Rectangle rect1 = new Rectangle();
int area = rect1.rectArea();
System.out.println("Area="+area);
}
}

This will initialize length and width to 1. This will initialize length and width to 0.
Hence the output will be “Area=1” Hence the output will be “Area=0”

METHOD OVERLOADING
In java it is possible to create methods that have the same name but different parameter lists
and different definitions. This is called method overloading. It is used when objects are required to
perform similar tasks but using different input parameters. When we call a method in an object, Java
matches us the method name first and then the number and type of parameters to decide which one of
the definitions to execute. This process is known as polymorphism. We can overload any method in a
class, including the constructor.

S4 CT/CHE - OOP Java - Module 1 Page 13 of 25


The example given below has a class Polygon in which the method area is overloaded. For
three objects namely circle, square and rectangle, based on the supplied parameters, the proper method
is executed and the area is displayed.

class Polygon
{
void area(double r) // for circle
{
System.out.println("Circle Area=" + (3.14*r*r));
}

void area(int a) // for square


{
System.out.println("Square Area=" + (a*a));
}

void area(int l, int w) // for rectangle


{
System.out.println("Rectangle Area=" + (l*w));
}

public static void main(String[] args)


{
Polygon circle = new Polygon();
circle.area(2.5);

Polygon square = new Polygon();


square.area(2);

Polygon rectangle = new Polygon();


rectangle.area(5,3);
}
}

The output of the above program will be;


Circle Area=19.625
Square Area=4
Rectangle Area=15

An example with overloaded constructors is given below.

class Rectangle
{
int length, width;

Rectangle() // constructor 1: default constructor


{
length=0;
width=0;
}

S4 CT/CHE - OOP Java - Module 1 Page 14 of 25


Rectangle(int x) // constructor 2: constructor with one parameter
{
length=width=x;
}

Rectangle(int x, int y) // constructor 3: constructor with two


parameters
{
length=x;
width=y;
}

int rectArea()
{
return (length*width);
}
public static void main(String[] args)
{
Rectangle rect1 = new Rectangle();
int area1 = rect1.rectArea();
System.out.println("Rect1 Area=" + area1);

Rectangle rect2 = new Rectangle(2);


int area2 = rect2.rectArea();
System.out.println("Rect2 Area=" + area2);

Rectangle rect3 = new Rectangle(2,3);


int area3 = rect3.rectArea();
System.out.println("Rect3 Area=" + area3 );
}
}

This will give the output as follows.


Rect1 Area=0
Rect2 Area=4
Rect3 Area=6

This is because rect1 is created with constructor 1, rect2 with constructor 2 and rect3 with
constructor 3.

STATIC MEMBERS (STATIC VARIABLES AND METHODS)


Basically a class contains two sections; variables and methods. These are called instance
variables and instance methods. This is because every time the class is instantiated, a new copy of
each of them is created. Suppose we assume that we want to define a member that is common to all the
objects and accessed without using a particular object. That is, the member belongs to the class as a
whole rather than the objects created from the class. Such members can be defined as follows.
static int count;
static int max(int x, int y) {.....}

S4 CT/CHE - OOP Java - Module 1 Page 15 of 25


These are called static variables and static methods. Since these are associated with the class rather
than objects, these are also called class variables and class methods.
Static variables are used when we want to have a variable common to all objects of a class.
One common example is to have a variable that could keep a count of how many objects of a class
have been created. Java creates only one copy of the static variable and can be accessed even if it does
not have any objects.
Static methods can be accessed without using the objects. They can be called by other classes
also. Methods that are of general utility are usually declared as static methods. One such method from
the Java library is Math.sqrt(n). Here the method sqrt is a static method in the class Math.
● A static method can only call other static methods.
● They can only access static data.
● They cannot refer to this or super in any way.

class Queue
{
static int totalCount=0;
int count;

public void insert()


{
totalCount++;
count++;
}

public void delete()


{
totalCount--;
count--;
}

public void printCount()


{
System.out.println("Queue Count:" + count);
System.out.println("Total Count:" + totalCount);
}

public static void count()


{
System.out.println("Static Function");
System.out.println("Total Count:" + totalCount);
}
}

Here the variable totalCount is a static variable and is created only once. But the variable count is a
per object one.

Constants: Constant is a value that cannot be changed after assigning it. Java does not directly
support the constants. There is an alternative way to define the constants in Java by using the
non-access modifiers static and final.

S4 CT/CHE - OOP Java - Module 1 Page 16 of 25


The purpose of using the static modifier is to manage the memory. It also allows the variable to
be available without loading any instance of the class in which it is defined. The final modifier
represents that the value of the variable cannot be changed. It also makes the primitive data type
unchangeable. According to the Java naming convention the identifier name must be in capital letters.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
For example, price is a variable that we want to make constant.
static final double PRICE=432.78;

VISIBILITY MODIFIERS (ACCESS MODIFIERS/ ACCESS SPECIFIERS):


The visibility modifiers are used to define where the element is to be accessible or visible.
With this, we can restrict the access to a member variable or method from outside the class. For
example, we may not like the objects of a class to directly alter the value of a variable or access a
method.
There are five types of visibility modifiers in Java.
● Private
● Public
● Protected
● Default (friendly)
● Private protected
Private: A private member is accessible only within its own class. It has the highest degree of
protection. It cannot be inherited by the subclasses and hence not accessible in subclasses. This
modifier is applied by adding the keyword private before the member.
Eg:
private int number;
private void sum( ) { …… }
Public: Any member with this specifier is visible to the entire class and outside the class. Its keyword
is public.
Protected: Visible to all classes and subclasses in the same package and subclasses in other packages.
Its keyword is protected.
Default: If no modifier is specified, it is the default one. The members are accessible to the same
class, its subclasses and all classes in the same package.
Private protected: Access limited to the same class and subclasses in the same package. It is defined
by the keyword private protected.

S4 CT/CHE - OOP Java - Module 1 Page 17 of 25


PASSING AND RETURNING OBJECTS AS ARGUMENTS:
Although Java method is strictly passed-by-value, the effect differs between whether a
primitive type (int, float, etc) or a reference type is passed. When we pass a primitive type to a
method, it is passed by value. But when we pass an object to a method, it is passed as
call-by-reference.
While creating a variable of a class type, we only create a reference to an object. Thus, when
we pass this reference to a method, the parameter that receives it will refer to the actual object itself.
Changes to the object inside the method do reflect the object used as an argument.
In the example given below, the main class has a method which accepts and returns an object
of the Rectangle class. The changes in the data of the passed object inside this method alter the actual
data. This is because the reference to the actual object is passed to the method. It returns an object
also.

class Rectangle
{
int length, breadth;

void setData(int l, int b)


{
length=l;
breadth=b;
}

void printData()
{
System.out.println(" Length of the rectangle= "+length);
System.out.println(" Breadth of the rectangle= "+breadth);
System.out.println(" Length of the rectangle=
"+(length*breadth));
}
}

class PassObject
{
static Rectangle changeData(Rectangle rect, int l, int b)
S4 CT/CHE - OOP Java - Module 1 Page 18 of 25
{
rect.setData(l,b);
return rect;
}
public static void main(String[] args)
{
Rectangle r1 = new Rectangle();
r1.setData(5,2);
System.out.println("r1 data - before change:");
r1.printData(); // 5,2,10

Rectangle r2 = new Rectangle();


r2 = changeData(r1, 6, 3);

System.out.println("r1 data - after change:");


r1.printData(); // 6,3,18
System.out.println("r2 data - from r1:");
r2.printData(); // 6,3,18

r2.setData(7,3);
System.out.println("r1 data - after r2 data is changed:");
r1.printData(); // 7,3,21
}
}

Output of the above program:


r1 data - before change:
Length of the rectangle= 5
Breadth of the rectangle= 2
Length of the rectangle= 10
r1 data - after change:
Length of the rectangle= 6
Breadth of the rectangle= 3
Length of the rectangle= 18
r2 data - from r1:
Length of the rectangle= 6
Breadth of the rectangle= 3
Length of the rectangle= 18
r1 data - after r2 data is changed:
Length of the rectangle= 7
Breadth of the rectangle= 3
Length of the rectangle= 21

Here the change passed object affects r1. Also the change in r2 affects r1. All of these mean
that the objects are passed by reference, rather than by value.

Defining a constructor that takes an object of its class as a parameter


One of the most common uses of object parameters involves constructors. Frequently, in
practice, there is a need to construct a new object so that it is initially the same as some existing

S4 CT/CHE - OOP Java - Module 1 Page 19 of 25


object. To do this, either we can use the Object.clone( ) method or define a constructor that takes an
object of its class as a parameter. Such a constructor just copies the contents of the passed object to the
new one. This constructor is called a copy constructor. A copy constructor in a Java class is a
constructor that creates an object using another object of the same Java class. That's helpful when we
want to copy a complex object that has several fields, or when we want to make a deep copy of an
existing object.
Example:
class Box {
double width, height, depth;

Box(Box ob) // copy constructor


{
width = ob.width;
height = ob.height;
depth = ob.depth;
}

Box(double w, double h, double d)


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

double volume()
{
return width * height * depth;
}
}

public class CopyConsTest


{
public static void main(String args[])
{
// Creating a box with all dimensions specified
Box mybox = new Box(10, 20, 15);

// Creating a copy of mybox


Box myclone = new Box(mybox);

double vol;

// Get volume of mybox


vol = mybox.volume();
System.out.println("Volume of mybox is " + vol);

// Get volume of myclone


vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
}
}
S4 CT/CHE - OOP Java - Module 1 Page 20 of 25
Array of Objects:
An array is a group of homogenous, contiguous or related data items that share a common
name. Each value is called an element. The values are accessed by the form array_name[index] where
the index represents the relative position of the element in the array, starting from 0. Arrays can be
single dimensional or multidimensional. In a single dimensional array, each element is of a primitive
or user defined type. In multidimensional arrays each element is in turn an array.
An integer array can be declared by;
int number[ ];
where number is the array name. But it will not allocate memory for it. For memory allocation, we
need to define the array by using the new operator. This is done by;
number = new int[5];
Combining these two, we can write as a single statement.
int number[ ] = new int[5];
Similar to the array of primitive types, we can define the array of objects too. Here each element is a
reference to an object. All the objects should be of the same class.
Declaration:
class_Name[ ] array_name;
Instantiation:
class_Name[ ] array_name = new class_Name[5];
Here each element can be initialized and accessed by using array name and index, similar to primitive
arrays.
Example:
class Employee
{
int emp_id;
String emp_name;
float salary;

Employee (int id, String name, float sal)


{
emp_id = id;
emp_name = name;
salary = sal;
}
void displayDetails()
{
System.out.println(emp_name + " has a salary of Rs. "+ salary + "
and his ID is "+ emp_id);
}
}

class ArrayObjects
{

public static void main(String args[])


{
Employee [] emp_arr = new Employee[4];
emp_arr [0] = new Employee(1001,"Martin", 15000);
S4 CT/CHE - OOP Java - Module 1 Page 21 of 25
emp_arr [1] = new Employee(1004,"Raj", 14000);
emp_arr [2] = new Employee(1008,"Rahul", 16000);

for (int i=0; i<3; i++)


{
emp_arr[i].displayDetails();
}
}
}

This will have the output;


Martin has a salary of Rs. 15000.0 and his ID is 1001
Raj has a salary of Rs. 14000.0 and his ID is 1004
Rahul has a salary of Rs. 16000.0 and his ID is 1008

Exception Handling:
An exception is a condition that is caused by a run-time error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object and
throws it (ie, informs us that an error has been encountered). If the exception is not caught and handled
properly, the interpreter will display an error message and will terminate the execution. If we want the
program to continue with the execution of the remaining code, then we should catch the exception
object thrown by the error condition and then display appropriate messages for corrective actions. This
task is known as exception handling. The steps of exception handling are given below.
1. Find the problem area (Hit the exception).
2. Inform that the error has occurred (Throw the exception).
3. Receive the error information (Catch the exception).
4. Take corrective actions (Handle the exception).

Exceptions in Java can be classified into two types;


1. Checked Exceptions: These exceptions are explicitly handled in the code itself with the help
of try-catch blocks.
2. Unchecked Exceptions: These exceptions are handled by the Java Virtual Machine.

Some common exceptions are;

S4 CT/CHE - OOP Java - Module 1 Page 22 of 25


Syntax of Exception Handling:
………….
………….
try
{
statement; // which may generate an exception
}
catch (Exception-Type e)
{
statement; // processes the exception
}
……….
……….

The statements that may generate an exception are put into the try block. Next to the try block,
the handlers are fixed by using the catch keyword. The catch block is similar to a method with one
argument. The catch block accepts an object of a particular type of exception that is specified along
with it. Divided by Zero Exception is an example for Arithmetic Exception. An example program with
such an exception is given below.

S4 CT/CHE - OOP Java - Module 1 Page 23 of 25


import java.util.Scanner; // to use keyboard input
class DivideByZeroException
{
public static void main(String[] args)
{
int x,y;
//Create scanner object to obtain input from keyboard
Scanner input=new Scanner(System.in);

try
{
System.out.print("Enter first integer : ");
x=input.nextInt(); //Read first integer
System.out.print("Enter second integer : ");
y=input.nextInt(); //Read second integer
System.out.println(x + " / " + y +" = " + (x/y));
}
catch(ArithmeticException e)
{
System.out.println("Error: Division by zero not
possible!!");
}
}
}

Here if the value of the variable y is zero, the expression x/y will throw an arithmetic exception. It is
caught by the catch block and prints the error message.
If there is no exception, or if the catch block has been executed due to an exception, the
program will continue with the next statement after the catch block.

Multiple Catch Statements:


If the try block may throw different types of exceptions we can define that many catch blocks after the
try block. The syntax is shown below.
………….
………….
try
{
statement; // which may generate an exception
}
catch (Exception-Type-1 e)
{
statement; // processes the exception type 1
}
catch (Exception-Type-2 e)
{
statement; // processes the exception type 2
}
catch (Exception-Type-3 e)
{
S4 CT/CHE - OOP Java - Module 1 Page 24 of 25
statement; // processes the exception type 3
}
……….
……….

Using Finally Statement


A statement known as a finally statement, can be used to handle an exception that is not caught
by any of the previous catch statements. It can be added just after the try block or after the last catch
block. The advantage of finally is that it is guaranteed to execute, regardless of whether or not an
exception is thrown. Hence we can use it to perform some house-keeping activities such as closing the
files and releasing the system resources.

…………. ………….
…………. ………….
try try
{ {
……… ………
} }
finally catch (....)
{ {
……… ……
} }
………. catch (....)
………. {
……
}
.
.
.
finally
{
………
}
……….
……….

**********************************

S4 CT/CHE - OOP Java - Module 1 Page 25 of 25

You might also like