OBJECT ORIENTED PROPGRAMMING USING JAVA · 1.2.2. Class: A class is a blueprint for a discrete...
Transcript of OBJECT ORIENTED PROPGRAMMING USING JAVA · 1.2.2. Class: A class is a blueprint for a discrete...
OBJECT ORIENTED PROPGRAMMING USING JAVA
Learning objectives
After undergoing the subject, students will be able to
Explain the concept of oops
Explain and execute the language construct concept
Debug and compile the program written in Java
Explain and implement class program
Explain and execute member function
Describe and implement inheritance concept
CHAPTER-1
1. Introduction and Features
1.1. Fundamentals of Object-Oriented Programming
OOP is the term used to describe a programming approach based on objects and classes. The
object-oriented paradigm allows us to organize software as a collection of objects that consist of
both data and behavior. This is in contrast to conventional functional programming practice that
only loosely connects data and behavior.
Since the 1980s the word 'object' has appeared in relation to programming languages, with
almost all languages developed since 1990 having object-oriented features. Some languages
have even had object-oriented features retro-fitted. It is widely accepted that object-oriented
programming is the most important and powerful way of creating software.
The object-oriented programming approach encourages:
Modularization: where the application can be decomposed into modules.
Software re-use: where an application can be composed from existing and new modules.
1.1.1 Procedure Oriented Programming VS. Object Oriented programming
Divided Into In POP, program is divided into small parts
called functions.
In OOP, program is divided into parts
called objects.
Importance In POP, Importance is not given to data but to
functions aswell as sequence of actions to be
done.
In OOP, Importance is given to the data rather
than procedures or functions because it works as
a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access Specifiers POP does not have any access specifier. OOP has access specifiers named Public, Private,
Protected, etc.
1.2. Object Oriented Programming Concept
Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies the software development and maintenance by providing some
concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
1.2.1. Object:
Any real world entity which can have some characteristics or which canperform some
work is called as Object.An object is an instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
Data Moving In POP, Data can move freely from function
to function in the system.
In OOP, objects can move and communicate with
each other through member functions.
Expansion To add new data and function in POP is not
so easy.
OOP provides an easy way to add new data and
function.
Data Access In POP, Most function uses Global data for
sharing that can be accessed freely from
function to function in the system.
In OOP, data cannot move easily from function to
function, it can be kept public or private so we can
control the access of data.
Data Hiding POP does not have any proper way for hiding
data so it is less secure.
OOP provides Data Hiding so provides more
security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator Overloading.
Examples Example of POP are : C, VB, FORTRAN,
Pascal.
Example of OOP are : C++, JAVA, VB.NET,
C#.NET.
1.2.2. Class:
A class is a blueprint for a discrete entity (object) that contains attributes and behavior.
The class defines the object's basic structure; at runtime, your application creates an
instance of the object.
1.2.3. Encapsulation and Data abstraction:
Wrapping of data and functions into a single unit is known as encapsulation. The data is
not accessible to the outside world and only those functions which are wrapping in the
class can access it. This insulation of the data from direct access by the program is called
data hiding or information hiding.
1.2.4. Data abstraction:
Data abstraction refers to, providing only needed information to the outside world and
hiding implementation details.
1.2.5. Inheritance:
Inheritance is the process by which objects of one class acquire the properties of objects
of another class. It supports the concept of hierarchical classification. Inheritance
provides re usability. This means that we can add additional features to an existing class
without modifying it.
1.2.6. Polymorphism:
Polymorphism means ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of data
used in the operation. C++ supports operator overloading and function overloading.
Operator overloading is the process of making an operator to exhibit different behaviors
in different instances is known as operator overloading. Function overloading is using a
single function name to perform different types of tasks. Polymorphism is extensively
used in implementing inheritance.
1.2.7. Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is decided at
runtime.
1.2.8. Message Passing:
Objects communicate with one another by sending and receiving information to each
other message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function and the
information to be sent.
2. Application of OOPS
1.Object Oriented Distributed Database
2. Client-Server System
3. Hypertext, Hypermedia
4. Neural Networking and Parallel Programming
5. Decision Support and Office Automation Systems
6. CIM/CAD/CAM Systems
7. AI and Expert Systems
3. Introduction of eclipse IDE for developing programs in Java.
Eclipse is more than an IDE; it's an entire development ecosystem. This section is a brief hands-
on introduction to using Eclipse for Java development.
3.1. Components of eclipse developing environment
The Eclipse development environment has four main components:
Workspace
Projects
Perspectives
Views
The primary unit of organization in Eclipse is the workspace. A workspace contains all of
your projects. A perspective is a way of looking at each project (hence the name), and within a
perspective are one or more views.
Figure 2 shows the Java perspective, which is the default perspective for Eclipse. You see this
perspective when you start Eclipse.
Figure 2. Eclipse Java perspective
The Java perspective contains the tools that you need to begin writing Java applications. Each
tabbed window shown in Figure 2 is a view for the Java perspective. Package Explorer and
Outline are two particularly useful views.
The Eclipse environment is highly configurable. Each view is dockable, so you can move it
around in the Java perspective and place it where you want it. For now, though, stick with the
default perspective and view setup.
Create a project
Follow these steps to create a new Java project:
1. Click File > New > Java Project... to start the New Java Project wizard, shown in Figure
3.
Figure 3. New Java Project wizard
2. Enter Tutorial as the project name and use the workspace location that you opened when
you opened Eclipse.
3. Verify the JDK that you're using.
4. Click Finish to accept the project setup and create the project.
You have now created a new Eclipse Java project and source folder. Your development
environment is ready for action.
Multiple choice questions
1. Class is a collection of ______ objects.
a. Similar b. dissimilar
2. _____ is an object oriented programming language.
a. C b. Pascal c. Java
3. Who is the developer of JAVA language?
a. Dennis Ritchie b. James Gosling
Short answer questions
1. What is OOPS?
2. Write basic concepts of OOPS?
3. What is a class?
4. What is an object?
5. What is Encapsulation?
6. What is polymorphism?
7. What is eclipse?
Long answer questions
1. What is OOP explain OOP concept in detail?
2. Difference between object oriented programming and procedure oriented programming.
CHAPTER-7 Exception Handling
1. Exception Handling
1.1Exceptions
Exceptions are events that occur during the execution of programs that disrupt the normal flow
of instructions (e.g. divide by zero, array access out of bound, etc.). In Java, an exception is an
object that wraps an error event that occurred within a method and contains information about
the error and its types.
1.2Exception Handling
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime
errors so that normal flow of the application can be maintained. In this page, we will learn about
Java exceptions, its type and the difference between checked and unchecked exceptions.
2. Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes, we will look after them first
and then we will write a simple program showing how to use them for exception handling.
2.1. throw
We know that if any exception occurs, an exception object is getting created and then Java
runtime starts processing to handle them. Sometime we might want to generate exception
explicitly in our code, for example in a user authentication program we should throw exception
to client if the password is null. throw keyword is used to throw exception to the runtime to
handle it.
2.2. throws
When we are throwing any exception in a method and not handling it, then we need to
use throws keyword in method signature to let caller program know the exceptions that might be
thrown by the method. The caller method might handle these exceptions or propagate it to it’s
caller method using throws keyword. We can provide multiple exceptions in the throws clause
and it can be used with main() method also.
2.3. try-catch
We use try-catch block for exception handling in our code. try is the start of the block and catch
is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try
and try-catch block can be nested also. catch block requires a parameter that should be of type
Exception. Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try {
//code that may throw exception
} catch (Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
} finally {}
2.4.finally – finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that will not
get closed, so we can use finally block. finally block gets executed always, whether
exception occurred or not.
Let’s see a simple programing showing exception handling in java.
package com.journaldev.exceptions;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExceptionHandling {
public static void main(String[] args) throws FileNotFoundException, IOException {
try{
testException(-5);
testException(-10);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
System.out.println("Releasing resources");
}
testException(15);
}
public static void testException(int i) throws FileNotFoundException, IOException{
if(i < 0){
FileNotFoundException myException = new
FileNotFoundException("Negative Integer "+i);
throw myException;
}else if(i > 10){
throw new IOException("Only supported for index 0 to 10");
}
}
}
Output of above program is:
java.io.FileNotFoundException: Negative Integer -5
at
com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:24)
at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:10)
Releasing resources
Exception in thread "main" java.io.IOException: Only supported for index 0 to 10
at
com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:27)
at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:19)
Notice that testException() method is throwing exception using throw keyword and method
signature uses throws keyword to let caller know the type of exceptions it might throw. In main()
method, I am handling exception using try-catch block in main() method and when I am not
handling it, I am propagating it to runtime with throws clause in main method. Notice
that testException(-10) never gets executed because of exception and then execution of finally
block after try-catch block is executed. The printStackTrace() is one of the useful method in
Exception class and used for debugging purpose.
We can’t have catch or finally clause without a try statement.
A try statement should have either catch block or finally block, it can have both blocks.
We can’t write any code between try-catch-finally block.
We can have multiple catch blocks with a single try statement.
try-catch blocks can be nested similar to if-else statements.
We can have only one finally block with a try-catch statement.
3. Java Exception Hierarchy
As stated earlier, when any exception is raised an exception object is getting created. Java
Exceptions are hierarchical and inheritance is used to categorize different types of exceptions.
Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error
and Exception. Exceptions are further divided into checked exceptions and runtime exception.
3.1. Errors: Errors are exceptional scenarios that are out of scope of application and it’s
not possible to anticipate and recover from them, for example hardware failure, JVM
crash or out of memory error. That’s why we have a separate hierarchy of errors and
we should not try to handle these situations. Some of the common Errors are
OutOfMemoryError and StackOverflowError.
3.2. Checked Exceptions: Checked Exceptions are exceptional scenarios that we can
anticipate in a program and try to recover from it, for example FileNotFoundException.
4. Difference between Throw and throws
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No. Throw throws
1) Java throw keyword is used to explicitly throw an
exception.
Java throws keyword is used to declare an exception.
2) Checked exception cannot be propagated using throw
only.
Checked exception can be propagated with throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
5. Difference between final, finally and finalize
There are many differences between final, finally and finalize. A list of differences between final,
finally and finalize are given below:
No. Final finally finalize
1) Final is used to apply restrictions on class,
method and variable. Final class can't be
inherited, final method can't be overridden
and final variable value can't be changed.
Finally is used to place
important code, it will be
executed whether exception
is handled or not.
Finalize is used to perform
clean up processing just
before object is garbage
collected.
2) Final is a keyword. Finally is a block. Finalize is a method.
Multiple choice questions
1. Errors may broadly be classified into two categories ---and----.
2. The -----always executes when the try block exits.
3. An ------ is an error thrown by a class or method reporting an error in operation.
Very short answer questions
1. What is an exception?
2. What is an error?
3. What is Try Block or Catch Block?
4. What is Finally Block?
5. Explain the types of exception.
6. What is the difference between throw and throws keywords.
7. How to throw an exception
8. Explain the syntax of exception handling with example.
9. What is the difference between error and exception in Java?
Long answer questions
1.What is exception handling explain in detail?