Egge
Egge
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.
Syntax:
interface<interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Prof.Pratiksha Surpur
OOPS USING JAVA
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
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?
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:
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 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
User-defined Packages
These are the packages that are defined by the user.
The package keyword is used to create a package in 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).
Prof.Pratiksha Surpur
OOPS USING JAVA
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.
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.
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.
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.
Prof.Pratiksha Surpur
OOPS USING JAVA
Output:
Exception in thread main java.lang.ArithmeticException:/by zero
Rest of the code…
class ExceptionDemo
{
public static void main(String[] args)
{
try
{
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{
Prof.Pratiksha Surpur
OOPS USING JAVA
Example
// Step 1: Define the custom exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
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:
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