OOP Java Module 1 - 09022023
OOP Java Module 1 - 09022023
OOP Java Module 1 - 09022023
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.
Representation of an Object
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.
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
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.
High Performance:
With the help of bytecode, the Java speed is comparable to C and C++.
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
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.
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)
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.
The process of building and running a Java application program is given in the figure below.
void printDetails()
{
System.out.println("Room length: " + length);
System.out.println("Room breadth: " + breadth);
System.out.println("Room area: " + (length*breadth));
}
}
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 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
{
Here the Room class contains two floating point variables length and breadth.
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’.
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;
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);
}
}
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); }
} }
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.
class Polygon
{
void area(double r) // for circle
{
System.out.println("Circle Area=" + (3.14*r*r));
}
class Rectangle
{
int length, width;
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);
This is because rect1 is created with constructor 1, rect2 with constructor 2 and rect3 with
constructor 3.
class Queue
{
static int totalCount=0;
int count;
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.
class Rectangle
{
int length, breadth;
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
r2.setData(7,3);
System.out.println("r1 data - after r2 data is changed:");
r1.printData(); // 7,3,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.
double volume()
{
return width * height * depth;
}
}
double vol;
class ArrayObjects
{
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).
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.
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.
…………. ………….
…………. ………….
try try
{ {
……… ………
} }
finally catch (....)
{ {
……… ……
} }
………. catch (....)
………. {
……
}
.
.
.
finally
{
………
}
……….
……….
**********************************