0% found this document useful (0 votes)
26 views32 pages

OOP Using JAVA Unit-III

This document covers Object-Oriented Programming (OOP) concepts in Java, focusing on interfaces, packages, and exception handling. It explains the differences between interfaces and abstract classes, how to define and implement interfaces, and the structure and usage of packages in Java. Additionally, it discusses exception handling, its benefits, and the classification of errors in Java programming.

Uploaded by

Varaprasad Mella
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views32 pages

OOP Using JAVA Unit-III

This document covers Object-Oriented Programming (OOP) concepts in Java, focusing on interfaces, packages, and exception handling. It explains the differences between interfaces and abstract classes, how to define and implement interfaces, and the structure and usage of packages in Java. Additionally, it discusses exception handling, its benefits, and the classification of errors in Java programming.

Uploaded by

Varaprasad Mella
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OOP using Java

UNIT-III
Interface: Interfaces VS Abstract classes, defining an interface, implement interfaces, accessing
implementations through interface references, extending interface;
Packages: Defining, creating and accessing a package, understanding CLASSPATH, importing
packages
Exception Handling: Benefits of exception handling, the classification of exceptions, exception
hierarchy, checked exceptions and unchecked exceptions, usage of try, catch, throw, throws and
finally, rethrowing exceptions, exception specification, built in exceptions, creating own
exception sub classes

Interfaces VS Abstract Classes

Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given
below.

Abstract Class Interfaces


1. Abstract class can have abstract and 1. Interface can have only abstract
non-abstract methods. methods. Since Java 8, it can have
default and static methods also.
2. Abstract class doesn't support 2. Interface supports multiple
multiple inheritance. inheritance.
3. Abstract class can have final, non- 3. Interface has only static and final
final, static and non-static variables. variables.
4. Abstract class can provide the 4. Interface can't provide the
implementation of interface. implementation of abstract class
5. The abstract keyword is used to 5. The interface keyword is used to
declare abstract class. declare interface.
6. An abstract class can extend another 6. An interface can extend another
Java class and implement multiple Java Java interface only.
interfaces.

7. An abstract class can be extended 7. An interface can be implemented


using keyword "extends". using keyword "implements".

8. A Java abstract class can have class 8. Members of a Java interface are
members like private, protected, etc. public by default.

1
OOP using Java

Example: Example:
public abstract Shape public interface Drawable
{ {
public abstract void draw(); void draw();
} }

INTERFACES

An interface is a special case of abstract class, which contains all the final
variables and abstract methods (methods without their implementation). An interface
specifies what a class must do, but not how to do.

Using the keyword interface, we can fully abstract a class interface from its
implementation. Interfaces are syntactically similar to classes, but they lack instance
variable, and their methods are declared without anybody. Once it is defined, any
number of classes can implement an interface. Also, one class can implement any
number of interfaces.

Defining interface

An interface is defined much like a class. This is the general form of an


interface:

access interface interface_name


{
type final_varname1=value;
type final_varname2=value;
....
Returntype method-name1(parameter_list);
returntype method-name2(parameter_list);
....
}

Here, access is either public or not used. Interface_name can be any valid
identifier. Methods which are declared have no bodies. They end with a semicolon
2
OOP using Java

after the parameter list. They are explicitly abstract methods. Variables are implicitly
final and static, meaning they cannot be changed by the implementing class. They
must be initialized with a constant value. All the methods and variable are implicitly
public if the interface, itself is declared as public.

Example:
interface Item
{
static final int code=1001;
static final String name=”Fan”;
void display(); //abstract method
}
Note that the code for the method is not included in the interface and the
method declaration simply ends with a semicolon. The class that implements this
interface must define the code for the method.

Extending Interfaces

Like classes, interfaces can also be extended. That is, an interface can be sub
interfaced from other interfaces. The new sub interface will inherit all the members
of the super interface in the manner similar to sub classes. This is achieved using the
keyword extends as shown in below.

interface name2 extends name1


{
Body of name2;
}
Consider the following example,

interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemConstants
{
void display();

3
OOP using Java

}
class Display implements Item
{
public void display()
{
System.out.println(code + “ “ + name);
}
}
Implementing Interfaces

Once an interface has been defined, one or more classes can implement that
interface. To implement an interface, include the implements clause in a class
definition, and then create the methods defined by the interface. The general form of
a class that includes the implements clause looks like this:

class class_nameimplements interface_name


{
Body of class name
}
Here the class class_name“implements” the interface interface_name.

When a class implements more than one interface, they are separated by a
comma. The implementation of interfaces can take various forms as illustrated
below.

4
OOP using Java

Accessing Interface Variables

Interfaces can also be used to declare a set of constants that can be used in
different classes. The constant values will be available to any class that implements
the interface. The values can be used in any method, as part of any variable
declaration, or anywhere where we can use a final value.

Example

interface A
{
int m=10;
int n=50;
}
class B implements A
{
void method(int size)
{
------------------
------------------
if(size<n)
-----------------
}
}

The following program illustrates the concept of interfaces in java.

//InterfaceTest.java
interface Area //Interface defined
{
final static float pi=3.14f;
float compute(float x,float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{

5
OOP using Java

return (x*y);
}
}
class Circle implements Area
{
public float compute(float x,float y)
{
return (pi*x*y);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Circle cir=new Circle();
Area area;
area=rect;
System.out.println("Area of Rectangle=" + area.compute(10,20));
area=cir;
System.out.println("area of circle=" + area.compute(10,10));
}
}
Output:

6
OOP using Java

Packages

A Package is a collection of classes, interfaces and sub-packages. A Sub


package in turns divides into classes, interfaces and sub-sub-packages, etc.
Learning about JAVA is nothing but learning about various packages. By
default one predefined package is imported for each and every java program and
whose name is java,lang.*.
Different types of packages
In java the packages are classified into two categories. They are
 Java API packages ( Predefined Packages)
 User defined Packages.

Java API packages


Java API provides a large number of classes grouped into different packages
according to their functionalities. They are shown in below.
Package Name Package Description

Java.lang.* This package is used for achieving the language


functionalities such as conversion of data from string to
fundamental data, displaying the results on to the console,
obtaining the garbage collector. This is the package
which is by default imported for each and every java
program.

Java.io.* This package is used for developing file handling


applications, such as , opening the file in read or write
mode, reading or writing the data, etc.

Java.awt.* This package is used for developing GUI(Graphical User


Interface) components such as buttons, check boxes,
(abstract window
scroll boxes, etc.
toolkit)

7
OOP using Java

Java.applet.* This package is used for developing browser oriented


applications. In other words this package is used for
developing distributed applications. An applet is a java
program which runs in the context of www or browser.

Java.util.* This package is used for developing quality or reliable


applications in java. This package contains various
classes and interfaces which improves the performance of
J2ME applications. This package is also known as
collection framework.

Java.net.* This package is used for developing client server


applications.

Using System Packages


The packages are organized in a hierarchical structure as shown in below.

There are two ways of accessing the classes stored in a package. The first
approach is to use the fully qualified class name of the class that we want to use.
This is done in the following way.
Example: import java.awt.Colour
Note that awtis a package within the package java and the hierarchy is
representing by separating levels with dot.
8
OOP using Java

The second approach is importing all the classes in a package at a time. This
is done in the following way.
Example: import java.awt.*;
The statements,
import packagename.classname;
Or
import java.packagename.*;

Are known as import statements and must appear at the top of the file,
before any class declarations, import is a keyword.
Note: Whenever we create user defined package statement as a part of java
program, we must use package statement as a first executable statement.

User-defined packages

The users of the Java language can also create their own packages. They are called
user-defined packages. User defined packages can also be imported into other
classes and used exactly in the same way as the built-in packages.

Defining & creating package:

Step1:
Simply include a package command has the first statement in java source
file. Any class you declare within that file will belong to the specified package.
Syntax: package packagename;
E.g.: package mypack;
Step 2:
Next define the class that is to be put in the package and declare it as public.
Step 3:
Now store the classname.java file in the directory having the name same as
package name.

9
OOP using Java

Step 4:
File is to be compiled as follows.
C:\>javac –d . classname.java
which creates .class file in the directory. Java also supports the package
hierarchy, which allows grouping related classes into a package and then grouping
related packages into a larger package. We can achieve this by specifying multiple
names in a package statement, separated by dot.
i.e., package firstpackage.secondpackage;
Accessing Package
A java system package can be accessed either by using a fully qualified class
name or by using import statement. We generally use import statement.
Syntax:
import pack1[.pack2][.pack3].classname;
OR
import pack1[.pack2][.pack3].*;
Here pack1 is the top-level package, pack2 is the package which is inside in
pack1 and so on. In this way we can have several packages in a package hierarchy.
We should specify explicit class name finally. Multiple import statements are valid.
* indicates that the compiler should search this entire package hierarchy when it
encounters a class name.
Importing Packages
Java includes import statement to bring certain classes or entire package into
visibility. In a java source file import statement occurs immediately following
package statement and before any class definitions.
Syntax:
import pack1[.pack2].(classname/*);
Here pack1 is the name of the top-level package. Pack2 is the name of the
subordinate package separated by (.). finally, classname / * indicates whether the
java compiler should import the entire package or a part of it.

10
OOP using Java

Ex:
import java.util.Date.
Here java is main package; util is subordinate package, Date is the class
belongs to util package.
Example Program (User defined Package)
Step1:
PackEg.Java
package p1;
public class PackEg
{
public void display()
{
System.out.println(“Welcome to java packages”);
}
}
Step2:
Compile the above program by using the following syntax.
C:\>javac –d . PackEg.java
Then it creates a directory having the name of the package ( PackEg) and it
contains the .class file for our program.
Step3:
PackDemo.java
import p1.PackEg
class Display
{
public static void main(String args[])
{
PackEg p=new PackEg();
p.display();
}
}
Now we will get the output as “Welcome to Java Packages” as follows.

11
OOP using Java

Static Import
This feature eliminates the need of qualifying a static member with the class
name. the static import declaration is similar that of import. We can use the import
statement to import classes from packages and use them without qualifying the
package. The syntax for using the static import feature is as follows.
import static package-name.subpackage-name.class-name.*;
Example program illustrates the concept of using the static import statement.
import static java.lang.Math.*;
public class mathop
{
public void circle(double r)
{
double area=PI * r*r;
System.out.println("The area of the circle is : " + area);
}
public static void main(String args[])
{
mathop obj=new mathop();
obj.circle(2.3);
}
}

Output

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

12
OOP using Java

CLASSPATH:
The location of all the necessary files that are utilized by the application is
described by CLASSPATH. The CLASSPATH is used by the VM (Java Virtual
Machine) and Java Compiler to find the necessary files. The online Java Compiler
will fail to locate the necessary files if the CLASSPATH is not configured.
Configuring Java

Once Java is installed, we need to configure it by adding the Java path to


environment variable, PATH. The following are the steps to set the PATH
variable to the Java directory.

1. Right click on the My Computer icon and select the properties option from
the drop down menu. The system properties dialog box appears as shown in
below.

2. Select the Advanced tab to display the advanced tab page, as shown in
below.

13
OOP using Java

3. Click the Environmental Variables button to display the Environmental


variables dialog box as shown in below.

14
OOP using Java

4. The Environmental dialog box is divided into two sections.


 User variables
 System Variables.

Under the Systems Variable section, select the path option below the
variable column and click the Edit button. The Edit System Variable dialog
box appears as shown in below.

5. By default the path variable is already set to multiple locations. To set the
Java directory path to the Path variable, append the directory path in the
variable value text box, separated by a semi-colon, as shown in below.

******************************************************************
Exception Handling

An Exception is defined as ―”an abnormal error condition that arises


during our program execution”. When an Exception occurs in a program, the java
interpreter creates an exception object and throws it out as java exceptions, which
are implemented as objects of exception class. This class is defined in
java.langpackage. An Exception object contains data members that will store the
exact information about the runtime error (Exception) that has occurred.

Types of Errors

Errors may broadly classified into two categories.

 Compile-time errors
 Run-time errors.

Compile-Time Errors

15
OOP using Java

All syntax errors will be detected and displayed by the java compiler and
therefore these errors are known as compile-time errors. Whenever the compiler
displays an error, it will not create the .class file.

The following program is the illustration of Compile-time errors

class Error1
{
public static void main(String args[])
{
System.out.println("Hello Java") //Missing ;
}
}
When we compile the above program the java compiler displays the following error.

Runtime Errors

Sometimes, a program may compile successfully creating the .class file but
may not run properly. Such programs may produce wrong results due to wrong logic
or may terminate due to errors such as stack overflow.

The following program is the illustration of Run-time errors .

class Error2
{
public static void main(String[] args)
{
int a=10;
int b=5;
int c=5;
int x=a/(b-c); //Division by zero
System.out.println("x=" + x);
int y=a/(b+c);

16
OOP using Java

System.out.println("y=" + y);
}
}
Output:

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

Benefits of Exception Handling

1. Separation of Error Handling: It keeps the main logic separate from error-
handling code, making the program easier to read and maintain.
2. Error Propagation: Exceptions can be propagated up the call stack, allowing
higher-level methods to handle errors or fail gracefully.
3. Specific Error Handling: Multiple catch blocks allow handling different
types of exceptions distinctly, ensuring precise control over error
management.

4. Improved Debugging: Exception messages and stack traces help in


diagnosing and fixing issues quickly.
5. Custom Exceptions: Developers can create custom exceptions for specific
scenarios, improving clarity and control.
6. Code Flexibility: Exception handling allows developers to deal with runtime
errors dynamically, providing more flexibility in managing unexpected issues
without hardcoding error scenarios.
7. Resource Management: With try-catch-finally blocks, resources like file
handles, database connections, or network connections can be properly closed
or released, avoiding resource leaks.

17
OOP using Java

8. Reusable Error Handling: Exception handling mechanisms can be written


once and reused across different parts of the application, ensuring consistent
and efficient error management throughout the codebase.

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

Classification of Exception

Exceptions in java can be categorized into two types.

1. User defined Exception

2. Built in Exception

User defined Exception:

we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.

18
OOP using Java

Basically, Java custom exceptions are used to customize the exception according to
user need.

 Checked Exceptions:

These exceptions are explicitly handled in the code itself with the help of try-
catch blocks. Checked exceptions are extended from the java.lang.Exception class.

Ex: FileNotFoundException,IOException,ClassNotFoundExceptionetc..

 Unchecked Exceptions:

These exceptions are not essentially handled in the program code, instead the
JVM handles such exceptions. Unchecked exceptions are extended from the class
java.lang.RuntimeException.

The following table shows some common errors that are occurred in the java
programs.

Exception Type Cause of Exception


ArithemeticException Caused by the math errors such as
division by zero.
ArrayIndexOutOfBoundsException Caused by bad array indexes.
FileNotFoundException Caused by an attempt to access a non
existing file.
NumberFormatException Caused when a conversion between
strings and numbers fails.
NullPointerException Caused by referencing a null object.

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

Exception Hierarchy

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited
by two subclasses: Exception and Error. The hierarchy of Java Exception classes is
given below:

19
OOP using Java

Object:In Java, the exception handling hierarchy is structured around the throwable
class, but it ultimately traces back to the root class Object

Every class in Java, including exception classes, is a subclass of Object. This


means that all exceptions inherit the basic functionality of the Object class.

Throwable:The Throwable class is the superclass of all errors and exceptions in the
Java language. Only objects that are instances of this class (or one of its subclasses)
are thrown by the Java Virtual Machine or can be thrown by the Java throw
statement.

The class at the top of the exception class hierarchy is the Throwable class,
which is a direct subclass of the Object class. Throwable has two direct subclasses –

1. Exception and

2. Error.

20
OOP using Java

Exception:An exception in Java is an error that occurs while a program is running,


disrupting the normal flow of instructions.
When an exception occurs, an exception object is created that contains
information about the error. The runtime system then looks for a method to handle
the exception.
Exceptions are classified into two types

1.Checked Exception

2.Unchecked Exception

Checked Exception:

These exceptions are explicitly handled in the code itself with the help of try-catch
blocks. Checked exceptions are extended from the java.lang.Exception class.

Unchecked Exception:

These exceptions are not essentially handled in the program code, instead the JVM
handles such exceptions. Unchecked exceptions are extended from the class
java.lang.RuntimeException.

Some of the Exceptions are:

S Exception Description
no
1 Arithmetic exception It is thrown when an exceptional
condition has occurred in an
arithmetic operation.
2 ArrayIndexOutOfBounds It is thrown to indicate that an
Exception array has been accessed with an
illegal index. The index is either
negative or greater than or equal
to the size of the array.
3 ClassNotFoundException This Exception is raised when we
try to access a class whose
definition is not found.
4 FileNotFoundException This Exception is raised when a
file is not accessible or does not
open.

21
OOP using Java

5 IOException It is thrown when an input-output


operation failed or interrupted
6 InterruptedException It is thrown when a thread is
waiting, sleeping, or doing some
processing, and it is interrupted
7 NoSuchMethodException It is thrown when accessing a
method which is not found.
8 NullPointerException This exception is raised when
referring to the members of a null
object. Null represents nothing
9 NumberFormatException This exception is raised when a
method could not convert a string
into a numeric format.
10 StringIndexOutOfBoundsException It is thrown by String class
methods to indicate that an index
is either negative than the size of
the string.

Errors:Represents serious problems that a reasonable application should not try to


catch. Errors usually indicate severe issues with the runtime environment or the
system itself.
or
Errors are usually caused by serious problems that are outside the control of the
program, such as running out of memory or a system crash. Errors are represented
by the Error class and its subclasses.

S NO Error Description
1. StackOverflowError Thrown when the call stack overflows due to too
many method invocations.
2. VirtualMachineError It's a self-defensive mechanism employed by the
JVM to prevent entire application from crashing
3. OutOfMemoryError Thrown when the Java Virtual Machine (JVM)
runs out of memory

22
OOP using Java

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

Usage of try, catch, throw, throws and finally,rethrowing

The basic concepts of exception handling are throwing an exception and


catching it. This illustrates in the following figure.

Java uses the keywords try and catch to handles the exceptions in the java programs.

try block:

The statements that produces exception are identified in the program and the
statements are placed in try block.

Syntax:

try
{
//Statements that causes Exception
}

catch block:

The catch block is used to process the exception raised. The catch block is
placed immediately after the try block.

Syntax:
catch(ExceptionTypeex_ob)

23
OOP using Java

{
//Statements that handle Exception
}
The following program illustrates the use of using the try and catch blocks in the
java programs.

class Error3
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c); //Division by zero
System.out.println("x=" + x);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero error occured");
}
y=a/(b+c);
System.out.println("y=" + y);
}
}

Output

24
OOP using Java

Note that the program did not stop at the point of exception condition. It
catches the error condition, prints the error message.

Throws Clause:

Even if the programmer is not handling runtime exceptions, the Java compiler will
not give any error related to runtime exceptions. But the rule is that the programmer
should handle checked exceptions. In case the programmer does not want to handle
the checked exceptions, he should throw them out using throws clause. Otherwise,
there will be an error flagged by Java compiler.

Example : Write a program which shows the use of throws clause

import java.io.*;

class Sample

//instance variable

private String name;

//method to accept name

void accept() throws IOException

//to accept data from keyboard

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("enter name:");

name=br.readLine();

//method to display name

void display()

25
OOP using Java

System.out.println("name:"+name);

class ex1

public static void main(String args[]) throws IOException

Sample s=new Sample();

s.accept();

s.display();

Output:

In this program, we are using throws clause to throw out an exception Without
handling it, from a method".

Throw Clause:

There is also a throw statement available in Java to throw an exception explicitly


and catch it.In the following program, we are creating an object of
NUllPointerExceptionclass and throwing it out of try block, as shown here
26
OOP using Java

throw new NullpointerEXception("Exception data");

In the above statement, NullPointerException class object is created and


'Exception data' is stored into its object. Then it is thrown using throw statement.
Now, we can 'catch it using catch block as:

catch(NullpointerException ne)

Example : Write a program that shows the use of throw clause for throwing the
nullPointerException

import java.lang.*;
//using throw
class Sample
{
static void demo()
{
try
{
System.out.println("Inside demo()");
throw new NullPointerException("Exception data");
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
class ThrowDemo
{
public static void main(String args[])
{
Sample.demo();

27
OOP using Java

}
}
output:

Re-throwing an Exception

When an exception occurs in a try block, it is caught by a catch block. This means
that the thrown exception is available to the catch block. The following code shows
how to re-throw the same exception out from the catch block.

try

throw exception;

catch(Exception obj)

throw exception; //re-throw the exception out

Example : Write a program to throw the StringlndexOutOfBoundsException

import java.lang.*;
class A
{
void method1()
{

28
OOP using Java

try
{
String str="hello";
char ch=str.charAt(5);
}
catch(StringIndexOutOfBoundsException sie)
{
System.out.println("please see the index is within the range");
throw sie; //rethrow the exception
}
}
}
class B
{
public static void main(String args[])
{
A a=new A();
try
{
a.method1();
}
catch(StringIndexOutOfBoundsException sie)
{
System.out.println("I caught rethrown exception");
}
}
}

Output:

29
OOP using Java

In this program, StringlndexOutOfBoundsException is thrown in methodl () of


class A whichcaught by catch block in that method. Then the catch block is re-
throwing it into main() method of class B.

Creating own Exception

In Java, we can create our own exceptions that are derived classes of the Exception
class. Creating our own Exception is known as custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception
according to user need.

In simple words, we can say that a User-Defined Exception or custom


exception is creating your own exception class and throwing that exception using
the ‘throw’ keyword.

In order to create a custom exception, we need to extend the Exception class


that belongs to java.lang package.

Reasons for use of Custom Exception

 Java exceptions cover almost all the general types of exceptions that may
occur in the programming. However, we sometimes need to create custom
exceptions.
 To catch and provide specific treatment to a subset of existing Java
exceptions.
 Business logic exceptions: These are the exceptions related to business logic
and workflow. It is useful for the application users or the developers to
understand the exact problem.

Steps to Create a Custom Exception:

1. Extend either Exception (for checked exceptions) or RuntimeException (for


unchecked exceptions).

2. Provide Constructors: Create constructors that can pass custom messages or


chain underlying exceptions.

30
OOP using Java

Example: Java program to create an own Exception

// Define a custom checked exception


public class InvalidAgeException extends Exception
{

public InvalidAgeException(String message)


{
super(message);
}
}

// Using the custom exception


public class Person
{

public void setAge(int age) throws InvalidAgeException


{
if (age < 18)
{
throw new InvalidAgeException("Age must be 18 or older.");
}
// logic to set age
}

public static void main(String[] args)


{
Person person = new Person();
Try
{
person.setAge(16);
}
catch (InvalidAgeException e)
{
System.out.println(e.getMessage());
}
}
}

Output:

31
OOP using Java

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

32

You might also like