MODULE 3
INTERFACE
Interface Fundamentals
An Interface in Java programming language is defined as an abstract type used
to specify the behavior of a class. A Java interface contains static constants and
abstract methods. A class can implement multiple interfaces. In Java, interfaces
are declared using the interface keyword. All methods in the interface are
implicitly public and abstract.
Syntax for Declaring Interface
To use an interface in your class, append the keyword “implements” after your
class name followed by the interface name.
interface {
//methods
}
A Java class can implement multiple Java Interfaces. It is necessary that
the class must implement all the methods declared in the interfaces.
Class should override all the abstract methods declared in the interface
The interface allows sending a message to an object without concerning
which classes it belongs.
Class needs to provide functionality for the methods declared in the
interface.
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. Class can extend
only one class but implement any number of interfaces
An interface cannot implement another Interface. It has to extend
another interface if needed.
An interface which is declared inside another interface is referred as
nested interface
At the time of declaration, interface variable must be initialized.
Otherwise, the compiler will throw an error.
The class cannot implement two interfaces in java that have methods
with same name but different return type.
Difference between Class and Interface
Class Interface
In class, you can instantiate variable In an interface, you can’t instantiate
and create an object. variable and create an object.
The interface cannot contain
Class can contain concrete(with
concrete(with implementation)
implementation) methods
methods
The access specifiers used with classes In Interface only one specifier is used-
are private, protected and public. Public.
Creating an Interface
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Internal addition by the compiler
The Java compiler adds public and abstract keywords before the interface
method. Moreover, it adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and
the methods are public and abstract.
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.
Implementing an Interface
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its
implementation is provided by Rectangle and Circle classes. In a real
scenario, an interface is defined by someone else, but its implementation
is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses
the interface.
File: TestInterface1.java
1. //Interface declaration: by first user
2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided
by method e.g. getDrawable()
16. d.draw();
17. }}
Output:
drawing circle
Using Interface References
interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
MyInterface obj = new InterfaceExample();
obj.display();
//obj.show();
}
}
Now, the program gets compiled and executed successfully.
Output
This is the implementation of the display method
Using Interface References
we have an interface named MyInterface with an abstract method
display().
We have a class with name InterfaceExample with a method (show()). In
addition to it, we are implementing the display() method of the
interface.
In the main method we are assigning the object of the class to the
reference variable of the interface and trying to invoke both the method.
interface MyInterface{
public static int num = 100;
public void display();
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
System.out.println("This is the implementation of the show method");
}
public static void main(String args[]) {
MyInterface obj = new InterfaceExample();
obj.display();
//obj.show();
}
}
Now, the program gets compiled and executed successfully.
Output
This is the implementation of the display method
Implementing Multiple Interfaces
The implements keyword is used to implement an interface.
The interface keyword is used to declare a special type of class that only
contains abstract methods.
To access the interface methods, the interface must be "implemented" (kinda
like inherited) by another class with the implements keyword (instead
of extends). The body of the interface method is provided by the "implement"
class.
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
public void myOtherMethod() {
System.out.println("Some other text...");
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
Output:
Some text...
Some other text...
Nested Interfaces
An interface, i.e., declared within another interface or class, is known as a
nested interface. The nested interfaces are used to group related
interfaces so that they can be easy to maintain. The nested interface must
be referred to by the outer interface or class. It can't be accessed directly.
Points to remember for nested interfaces
There are given some points that should be remembered by the java
programmer.
o The nested interface must be public if it is declared inside the interface,
but it can have any access modifier if declared within the class.
o Nested interfaces are declared static
Syntax of nested interface which is declared within the
interface
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
Syntax of nested interface which is declared within the
class
1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
TestNestedInterface1.java
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. } }
6. class TestNestedInterface1 implements Showable.Message{
7. public void msg()
8. {
9. System.out.println("Hello nested interface");
10.}
11. public static void main(String args[]){
12. Showable.Message message=new TestNestedInterface1();//
upcasting here
13. message.msg();
14. }
15.}
Output:
hello nested interface
Packages:
Package Fundamentals
A java package is a group of similar types of classes, interfaces and sub-
packages.
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that
they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
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).
D:\>javac -d . Simple.java
D:\>java mypack.Simple
Welcome to package
Output:Welcome to package
Importing Packages
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
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
The java.util.Scanner class is a simple text scanner which can parse
primitive types and strings using regular expressions. Following are the
important points about Scanner −
A Scanner breaks its input into tokens using a delimiter
pattern, which by default matches whitespace.
A scanning operation may block waiting for input.
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);
Output
Enter username
aa
Username is: aa
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package
will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
Static Import
The static import feature of Java 5 facilitate the java programmer to
access any static member of a class directly. There is no need to qualify it
by the class name.
Advantage of static import:
o Less coding is required if you have access any static member of a class
oftenly.
Disadvantage of static import:
o If you overuse the static import feature, it makes the program unreadable
and unmaintainable.
Simple Example of static import
1. import static java.lang.System.*;
2. class StaticImportExample{
3. public static void main(String args[]){
4.
5. out.println("Hello"); //Now no need of System.out
6. out.println("Java");
7. }
8. }
Output:Hello
Java
Autoboxing and Unboxing
The automatic conversion of primitive data types into its equivalent
Wrapper type is known as boxing and opposite operation is known as
unboxing. This is the new feature of Java5. So java programmer doesn't
need to write the conversion code.
Advantage of Autoboxing and Unboxing:
In Java, primitive data types are treated differently so do there
comes the introduction of wrapper classes where two components
play a role namely Autoboxing and Unboxing. Autoboxing refers to
the conversion of a primitive value into an object of the
corresponding wrapper class is called autoboxing. For example,
converting int to Integer class. The Java compiler applies
autoboxing when a primitive value is:
Passed as a parameter to a method that expects an
object of the corresponding wrapper class.
Assigned to a variable of the corresponding wrapper
class.
Simple Example of Autoboxing in java:
1. class BoxingExample1{
2. public static void main(String args[]){
3. int a=50;
4. Integer a2=new Integer(a);//Boxing
5.
6. Integer a3=5;//Boxing
7.
8. System.out.println(a2+" "+a3);
9. }
10. }
11.
Output:50 5
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into corresponding
primitive type, is known as Unboxing. Let's see the example of unboxing:
Unboxing on the other hand refers to converting an object of a
wrapper type to its corresponding primitive value. For example
conversion of Integer to int. The Java compiler applies to unbox
when an object of a wrapper class is:
Passed as a parameter to a method that expects a
value of the corresponding primitive type.
Assigned to a variable of the corresponding primitive
type.
1. class UnboxingExample1{
2. public static void main(String args[]){
3. Integer i=new Integer(50);
4. int a=i;
5.
6. System.out.println(a);
7. }
8. }
9.
Output:
50
Exception Handling
Exception Handling fundamentals
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 Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
Hierarchy of Java Exception classes
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:
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
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.
JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e)
7. {
8. System.out.println(e);
9. }
10. //rest code of the program
11. System.out.println("rest of the code...");
12. }
13.}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Using Multiple catch clauses
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-
catch block.
Points to remember
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.
Flowchart of Multi-catch Block
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
1. public class MultipleCatchBlock1 {
2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exce
ption occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Output:
Arithmetic Exception occurs
rest of the code
try blocks can be nested
using a try block inside another try block is permitted. It is called as
nested try block. Every statement that we enter a statement in try block,
context of that exception is pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try
block can handle the ArithemeticException (division by zero).
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one
error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12.//try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20.//exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26.//exception message
27. }
28.}
29. //catch block of parent (outer) try block
30.catch(Exception e3)
31. {
32.//exception message
33. }
34.....
Java Nested try Example
Example 1
Let's see an example where we place a try block within another try block
for two different exceptions.
NestedTryBlock.java
1. public class NestedTryBlock{
2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15. //inner try block 2
16. try{
17. int a[]=new int[5];
18.
19. //assigning the value out of array bounds
20. a[5]=4;
21. }
22. //catch block of inner try block 2
23. catch(ArrayIndexOutOfBoundsException e)
24. {
25. System.out.println(e);
26. }
27.
28. System.out.println("other statement");
29. }
30. //catch block of outer try block
31. catch(Exception e)
32. {
33. System.out.println("handled the exception (outer catch)");
34. }
35.
36. System.out.println("normal flow..");
37. }
38.}
Output:
Throwing an Exception
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has
some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception. We will discuss
custom exceptions
We can also define our own set of conditions and throw an exception
explicitly using throw keyword. For example, we can throw
ArithmeticException if we divide a number by another number. Here, we
just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
1. throw new exception_class("error message");
Let's see the example of throw IOException.
1. throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable.
For example, Exception is the sub class of Throwable and the user-defined
exceptions usually extend the Exception class.
Java throw keyword Example
Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts
an integer as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
TestThrow1.java
In this example, we have created the validate method that takes integer
value as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be
at least 18 years old.");
else {
System.out.println("Access granted - You are old enough!");
} }
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}}
Output:
Exception in thread "main" java.lang.ArithmeticException:
Access denied - You must be at least 18 years old.
Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
using finally
Java finally block is a block used to execute important code such as
closing the connection, etc.
Java finally block is always executed whether an exception is handled or
not. Therefore, it contains all the necessary statements that need to be
printed regardless of the exception occurs or not.
The finally block follows the try-catch block.
Flowchart of finally block
When an exception occurs and is handled by the catch
block
Example:
Let's see the following example where the Java code throws an exception
and the catch block handles the exception. Later the finally block is
executed after the try-catch block. Further, the rest of the code is also
executed normally.
TestFinallyBlock2.java
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. //below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(“data”);
8. } //handles the Arithmetic Exception / Divide by zero except
ion
9. catch(ArithmeticException e){
10. System.out.println("Exception handled");
11. System.out.println(e);
12. } //executes regardless of exception occured or not
13. finally {
14. System.out.println("finally block is always executed");
15. } System.out.println("rest of the code..."); } }
16.Output:
throws Keyword
The throws keyword is used to declare the list of exception
that a method may throw during execution of program. Any
method that is capable of causing exceptions must list all
the exceptions possible during its execution, so that
anyone calling that method gets a prior knowledge about
which exceptions are to be handled. A method can do so by
using the throws keyword.
1. public class TestThrows {
2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticExce
ption {
4. int div = m / n;
5. return div;
6. } //main method
7. public static void main(String[] args) {
8. TestThrows obj = new TestThrows();
9. try {
10. System.out.println(obj.divideNum(45, 0));
11. }
12. catch (ArithmeticException e){
13. System.out.println("\nNumber cannot be divided by 0");
14. }
15. System.out.println("Rest of the code.."); } }
16. Output:
Difference between throw and throws
throw throws
throw keyword is used to throws keyword is used to
throw an exception declare an exception possible
explicitly. during its execution.
throw keyword is followed throws keyword is followed by
by an instance of Throwable
one or more Exception class
class or one of its sub-
names separated by commas.
classes.
throws keyword is used with
throw keyword is declared
method signature (method
inside a method body.
declaration).
We can declare multiple
We cannot throw multiple
exceptions (separated by
exceptions using throw
commas) using throws
keyword.
keyword.
Java’s Built-in Exceptions
Java defines several exception classes inside the standard
package java.lang.
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java
programs, most exceptions derived from RuntimeException are
automatically available.
Java defines several other types of exceptions that relate to its various
class libraries. Following is the list of Java Unchecked RuntimeException.
Sr.No. Exception & Description
1
ArithmeticException
Arithmetic error, such as divide-by-zero.
2
ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3
ArrayStoreException
Assignment to an array element of an incompatible type.
4
ClassCastException
Invalid cast.