OOP Using JAVA Unit-III
OOP Using JAVA Unit-III
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
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.
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
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 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:
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
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)
-----------------
}
}
//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
7
OOP using Java
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.
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
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
14
OOP using Java
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
Types of Errors
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.
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.
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:
**************************************************************
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.
17
OOP using Java
*************************************************************
******
Classification of Exception
2. Built in 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 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
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
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.
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
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
************************************************************
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.
import java.io.*;
class Sample
//instance variable
System.out.print("enter name:");
name=br.readLine();
void display()
25
OOP using Java
System.out.println("name:"+name);
class ex1
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:
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)
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 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.
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.
30
OOP using Java
Output:
31
OOP using Java
******************************************************************
***
32