0% found this document useful (0 votes)
3 views12 pages

Egge

The document provides an overview of Java interfaces, explaining their purpose, declaration, and usage in achieving abstraction and multiple inheritance. It also covers Java packages, exception handling, and the differences between checked and unchecked exceptions, including custom exceptions. Additionally, it includes examples demonstrating the implementation of interfaces, exception handling, and the use of built-in packages.
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)
3 views12 pages

Egge

The document provides an overview of Java interfaces, explaining their purpose, declaration, and usage in achieving abstraction and multiple inheritance. It also covers Java packages, exception handling, and the differences between checked and unchecked exceptions, including custom exceptions. Additionally, it includes examples demonstrating the implementation of interfaces, exception handling, and the use of built-in packages.
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
You are on page 1/ 12

OOPS USING JAVA

UNIT-IV

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction.. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Java Interface also represents
epresents the IS IS-A relationship.
60.8MDifference between JDK, JRE, and JVM
It cannot be instantiated just like the abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
o It is used to achievee abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
interface<interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface

Prof.Pratiksha Surpur
OOPS USING JAVA

Java Interface Example


In this example, the Printable interface has only one method, and its implementation
is provided in the A6 class.

interface printable
{
void print();
}
class A implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A obj = new A();
obj.print();
}
}

Output: Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.

interface Printable
{
void print();
}
interface Showable

{
void show();
}
class A implements Printable,Showable
{
public void print()

Prof.Pratiksha Surpur
OOPS USING JAVA

{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A obj = new A();
obj.print(); obj.show();
}
}
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java, but
it is possible by an interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported


in the case of class because of ambiguity. However, it is supported in case of an
interface because there is no ambiguity. It is because its implementation is provided
by the implementation class.
As you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class A, so there is no ambiguity

Accessing the fields of an interface

In general, to create an object of an interface type you need to implement it and provide
implementation to all the abstract methods in it. When you do so, all the fields of the interface
are inherited by the implementing class, i.e. a copy of the fields of an interface are available in
the class that implements it.

Since all the fields of an interface are static by default, you can access them using the name of
the interface as −

Example

interfaceMyInterface{
publicstaticint num =100;
publicvoid display();
}
publicclassInterfaceExampleimplementsMyInterface{
publicstaticint num =10000;
publicvoid display(){
System.out.println("This is the implementation of the display method");
}
publicvoid show(){
System.out.println("This is the implementation of the show method");
}
publicstaticvoid main(String args[]){
InterfaceExample obj =newInterfaceExample();
System.out.println("Value of num of the interface "+MyInterface.num);

Prof.Pratiksha Surpur
OOPS USING JAVA

System.out.println("Value
"Value of num of the class ""+obj.num);
}
}

Output:

Value of num of the interface 100


Value of num of the class 10000

But, since the variables of an interface are final you cannot reassign values to them. If you try to
do so, a compile-time
time error will be generated.

Java Package
A java package is a group of similar types of classes, interfaces and sub
sub-packages.
packages.
Package in java
va can be categorized in two form, built-in
built package and user-defined
package.
There are many built-in
in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Types of packages:

Built-in
in Packages (System packages)
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library is divided into packages and classes.. Meaning you can either import a single
class (along with its methods and attributes), or a whol
wholee package that contain all the classes
that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:

Syntax
import package.name.Class;//
// Import a single class

Prof.Pratiksha Surpur
OOPS USING JAVA

import package.name.*;// Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:

Example
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read a complete line:

Example

Using the Scanner class to get user input:


import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}

These packages consist of a large number of classes which are a part of


Java API.Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines


primitive data types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like
Linked List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical
user interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

User-defined Packages
These are the packages that are defined by the user.
The package keyword is used to create a package in java.

How to compile java package


syntax
javac -d directory javafilename

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

Prof.Pratiksha Surpur
OOPS USING JAVA

How to run java package program


You need to use fully qualified name e.g. mypack.Simple to run the class.
Example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

To Compile: javac -d . Simple.java

To Run: java mypack.Simple


Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Prof.Pratiksha Surpur
OOPS USING JAVA

Suppose there are 10 statements in a Java program and an exception occurs at statement
5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be
executed. That is why we use exception handling in Java.

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered
as the unchecked exception. However, according to Oracle, there are three types of
exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword
1.try :The "try" keyword is used to specify a block where we should place
an exception code. It means we can't use try block alone. The try
block must be followed by either catch or finally.

2.catch :The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block alone. It
can be followed by finally block later.

3.finally :The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

4.throw :The "throw" keyword is used to throw an exception.

5.throws :The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

Syntax of Java try-catch


try
{

Prof.Pratiksha Surpur
OOPS USING JAVA

//code that may throw an exception


}
catch(Exception_class_Name ref)
{}

Syntax of try-finally block


try
{
//code that may throw an exception
}
finally
{}

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception
.
JavaExceptionExample.java
public class JavaExceptionExample
{
public static void main(String args[]) {
try
{
int data=100/0; //code that may raise exception
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code..."); //rest code of the program
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/by zero
Rest of the code…

In the above example, 100/0 raises an ArithmeticException which is handled by a try


catch block.

Program to demonstrate exception handling with try, catch and finally.(LAB


PROGRAM)

class ExceptionDemo
{
public static void main(String[] args)
{
try
{
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{

Prof.Pratiksha Surpur
OOPS USING JAVA

System.out.println("ArithmeticException =" + e.getMessage());


}
finally
{
System.out.println("This is the finally block");
}
}
}
Custom exception(User-defined exception)
Java provides us the facility to create our own exceptions which are basically derived classes
of Exception. Creating our own Exception is known as a custom exception in Java or user-
defined exception in Java. Basically, Java custom exceptions are used to customize the
exception according to user needs. In simple words, we can say that a User-Defined Custom
Exception or custom exception is creating your own exception class and throwing that
exception using the ‘throw’ keyword.
A custom exception in Java is an exception defined by the user to handle specific application
requirements. These exceptions extend either the Exception class (for checked exceptions) or
the RuntimeException class (for unchecked exceptions).

Example
// Step 1: Define the custom exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {

super(message);
}
}

// Step 2: Class that uses the custom exception


public class CustomExceptionExample {

// Method to check age for voting


public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is less than 18. Not eligible to vote.");

Prof.Pratiksha Surpur
OOPS USING JAVA

} else {
System.out.println("You are eligible to vote.");
}
}

// Main method
public static void main(String[] args) {
try {
checkAge(16); // Change this value to test different ages
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}

System.out.println("Program continues...");
}
}
Output:
Caught Exception: Age is less than 18. Not eligible to vote.
Program continues...

Prof.Pratiksha Surpur
OOPS USING JAVA

Java Multi-catch
catch block statements

A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi
multi-catch block.

o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
EXAMPLE:

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[55];
a[5]=30/0;
}
catch(ArithmeticException
(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");

Prof.Pratiksha Surpur
OOPS USING JAVA

}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:
Arithmetic Exception occurs
rest of the code

Prof.Pratiksha Surpur

You might also like