0% found this document useful (0 votes)
11 views

Module-4

The document discusses Java packages and interfaces, explaining their purpose in avoiding naming conflicts and controlling access to classes and interfaces. It details built-in and user-defined packages, provides examples of built-in packages, and illustrates how to define and implement interfaces. Additionally, it covers exception handling, including types of exceptions, using try-catch blocks, and the throw and throws statements for managing exceptions in Java programs.

Uploaded by

nischal3202
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Module-4

The document discusses Java packages and interfaces, explaining their purpose in avoiding naming conflicts and controlling access to classes and interfaces. It details built-in and user-defined packages, provides examples of built-in packages, and illustrates how to define and implement interfaces. Additionally, it covers exception handling, including types of exceptions, using try-catch blocks, and the throw and throws statements for managing exceptions in Java programs.

Uploaded by

nischal3202
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

MODULE - 4

Packages and Interfaces


Packages

In java packages are used to avoid naming conflict and to control the access of
class, interface, sub-classes, etc. A package can be defined as a group of similar
types of classes, sub-classes, interfaces or enumerations, etc. while using
packages it becomes easier to locate or find the related classes and packages
provides a good structure or outline of the project with a huge amount of
classes and files.
Packages are divided into two parts:

• Built-in packages: In java, we already have various pre-defined packages and


these packages contain large numbers of classes and interfaces that we used
in java are known as Built-in packages.

• User-defined packages: As the name suggests user-defined packages are a


package that is defined by the user or programmer.
Built-in packages
Examples of Built-in Packages
• java.sql: Provides the classes for accessing and processing data stored in a database. Classes
like Connection, DriverManager, PreparedStatement, ResultSet, Statement, etc. are part of this
package.
• java.lang: Contains classes and interfaces that are fundamental to the design of the Java
programming language. Classes like String, StringBuffer, System, Math, Integer, etc. are part of
this package.
• java.util: Contains the collections framework, some internationalization support classes,
properties, random number generation classes. Classes like ArrayList, LinkedList, HashMap,
Calendar, Date, Time Zone, etc. are part of this package.
• java.net: Provides classes for implementing networking applications. Classes like
Authenticator, HTTP Cookie, Socket, URL, URLConnection, URLEncoder, URLDecoder, etc. are
part of this package.
• java.io: Provides classes for system input/output operations. Classes like BufferedReader,
BufferedWriter, File, InputStream, OutputStream, PrintStream, Serializable, etc. are part of this
package.
• java.awt: Contains classes for creating user interfaces and for painting graphics and images.
Classes like Button, Color, Event, Font, Graphics, Image, etc. are part of this package.
Example

import java.util.Arrays;

public class MyClass {


public static void main(String args[]) {
int[] arr = { 40, 30, 20, 70, 80 };
Arrays.sort(arr);
System.out.printf("Sorted Array is = "+Arrays.toString(arr));
}
}

Output:

Sorted Array is = [20, 30, 40, 70, 80]


User-defined Package
• Java also allows you to create packages as per your need. These packages are
called user-defined packages.
• This is the general form of the package statement:
package pkg;

You can create a hierarchy of packages. To do so, simply separate each package
name from the one above it by use of a period. The general form of a
multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A Short Package Example
// A simple package class AccountBalance {
package MyPack; public static void main(String args[]) {
class Balance {
Balance current[] = new Balance[3];
String name;
double bal; current[0] = new Balance("K. J. Fielding", 123.23);
Balance(String n, double b) { current[1] = new Balance("Will Tell", 157.02);
name = n; current[2] = new Balance("Tom Jackson", -12.33);
bal = b; for(int i=0; i<3; i++)
} {
void show() { current[i].show();
if(bal<0) }
System.out.print("--> "); }
System.out.println(name + ": $" + bal);
}
}
}
This is file Protection.java: This is file Derived.java:
package p1;
public class Protection { package p1;
class Derived extends Protection {
int n = 1; Derived() {
private int n_pri = 2; System.out.println("derived constructor");
protected int n_pro = 3; System.out.println("n = " + n);
public int n_pub = 4; // class only
// System.out.println("n_pri = "4 + n_pri);
public Protection() { System.out.println("n_pro = " + n_pro);
System.out.println("base constructor"); System.out.println("n_pub = " + n_pub);
System.out.println("n = " + n); }
System.out.println("n_pri = " + n_pri); }
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
This is file Protection.java: This is file SamePackage.java:
package p1; package p1;
class SamePackage {
public class Protection {
SamePackage() {
int n = 1; Protection p = new Protection();
private int n_pri = 2; System.out.println("same package
protected int n_pro = 3; constructor");
System.out.println("n = " + p.n);
public int n_pub = 4;
// class only
public Protection() { // System.out.println("n_pri = " + p.n_pri);
System.out.println("base constructor"); System.out.println("n_pro = " + p.n_pro);
System.out.println("n = " + n); System.out.println("n_pub = " + p.n_pub);
}
System.out.println("n_pri = " + n_pri);
}
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
package p2;
class Protection2 extends p1.Protection {
Protection2() {
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
This is file OtherPackage.java:
package p2;
class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
// Demo package p1. // Demo package p2.
package p1; package p2;
// Instantiate the various classes in p1. // Instantiate the various classes in p2.
public class Demo { public class Demo {
public static void main(String args[]) {
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
Protection ob1 = new Protection(); OtherPackage ob2 = new OtherPackage();
Derived ob2 = new Derived(); }
SamePackage ob3 = new SamePackage(); }
}
}
Importing Packages

In a Java source file, import statements occur immediately following the package
statement(if it exists) and before any class definitions. This is the general form of
the import statement:
import pkg1[.pkg2].(classname|*);
package MyPack;
/* Now, the Balance class, its constructor, import MyPack.*;
and itsshow() method are public. class TestBalance {
This means that they canbe used by non-subclass public static void main(String args[]) {
code outside their package. /* Because Balance is public,
*/ you may use Balance class
public class Balance { and call its constructor. */
String name; Balance test = new Balance("J. J. Jaspers", 99.88);
double bal; test.show(); // you may also call show()
public Balance(String n, double b) { }
name = n; }
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
Interfaces
• Using the keyword interface, you can fully abstract a class’ interface from its
implementation.
• That is, using interface, you can specify what a class must do, but not how it
does it.
• Interfaces are syntactically similar to classes, but they lack instance variables,
and their methods are declared without any body.
• Once it is defined, any number of classes can implement an interface. Also, one
class can implement any number of interfaces.
• To implement an interface, a class must create the complete set of methods
defined by the interface. However, each class is free to determine the details of
its own implementation.
• By providing the interface keyword, Java allows you to fully utilize the “one
interface, multiple methods” aspect of polymorphism.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:

access interface name {


return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
• The methods that are declared have no bodies. They end with a semicolon after
the parameter list.
• They are, essentially, abstract methods; there can be no default
implementation of any method specified within an interface.
• Each class that includes an interface must implement all of the methods.
• Variables can be declared inside of interface declarations.
• They are implicitly final and static, meaning they cannot be changed by the
implementing class. They must also be initialized. All methods and variables are
implicitly public.
Implementing Interfaces

class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}
interface Callback {
void callback(int param);
}

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
Accessing Implementations Through Interface References

class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}

The output of this program is shown here:


callback called with 42
// Another implementation of Callback.
class TestIface2 {

class AnotherClient implements Callback { public static void main(String args[]) {


Callback c = new Client();
// Implement Callback's interface
AnotherClient ob = new AnotherClient();
public void callback(int p) {
c.callback(42);
System.out.println("Another version of callback"); c = ob; // c now refers to AnotherClient object

System.out.println("p squared is " + (p*p)); c.callback(42);

} }
}
} The output from this program is shown here:
callback called with 42
Another version of callback
p squared is 1764
Partial Implementations

If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract. For example:

abstract class Incomplete implements Callback {


int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
Nested Interfaces
An interface can be declared a member of a class or another interface. Such an interface is called a
member interface or a nested interface.
// A nested interface example.
// This class contains a member interface. class NestedIFDemo {
public static void main(String args[]) {
class A {
// use a nested interface reference
// this is a nested interface A.NestedIF nif = new B();
public interface NestedIF { if(nif.isNotNegative(10))
boolean isNotNegative(int x); System.out.println("10 is not negative");
} if(nif.isNotNegative(-12))
} System.out.println("this won't be displayed");
// B implements the nested interface. }
}
class B implements A.NestedIF {
public boolean isNotNegative(int x) {
return x < 0 ? false : true;
}
Exception Handling
An exception (or exceptional event) is a problem that arises during the
execution of a program. When an Exception occurs the normal flow of
the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions
are to be handled.

• An exception can occur for many different reasons. Following are


some scenarios where an exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications
or the JVM has run out of memory.
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus,
Throwable is at the top of the exception class hierarchy. Immediately below
Throwable are two subclasses that partition exceptions into two distinct
branches.
Example

class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}

java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Using try and catch
Although the default exception handler provided by the Java run-time system is
useful for debugging, you will usually want to handle an exception yourself.
Doing so provides two benefits.
First, it allows you to fix the error.
Second, it prevents the program from automatically terminating. Most users would
be confused (to say the least) if your program stopped running and printed a stack
trace whenever an error occurred! Fortunately, it is quite easy to prevent this.
To guard against and handle a run-time error, simply enclose the code that you
want to monitor inside a try block.
Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
Try block
The try block contains set of statements where an exception can occur. A try
block is always followed by a catch block, which handles the exception that
occurs in associated try block. A try block must be followed by catch blocks or
finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can
throw a exception, enclosed them in try block and handle that exception
Catch block
A catch block is where you handle the exceptions, this block must follow the try block. A single try
block can have several catch blocks associated with it. You can catch different exceptions in different
catch blocks.
When an exception occurs in try block, the corresponding catch block that handles that particular
exception executes. For example if an arithmetic exception occurs in try block then the statements
enclosed in catch block for arithmetic exception executes.
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) object e)
{
//error handling code
}
Example
class Exc2 { Output:
public static void main(String args[]) { Division by zero.
int d, a; After catch statement.
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Example of Multiple catch blocks
catch(ArithmeticException e){
class Example2{ System.out.println("Warning: ArithmeticException");
}
public static void main(String args[]){
catch(ArrayIndexOutOfBoundsException e){
try{ System.out.println("Warning: ArrayIndexOutOfBoundsException");
int a[]=new int[7]; }
a[4]=30/0; catch(Exception e){
System.out.println("Warning: Some Other exception");
System.out.println("First print statement in try block"); }
} System.out.println("Out of try-catch block...");
}
}

Output:
Warning: ArithmeticException
Out of try-catch block...
Example
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
}
catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
Nested try Statements
throw
• So far, you have only been catching exceptions that are thrown by the Java
run-time system.
• However, it is possible for your program to throw an exception explicitly,
using the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
Demonstrate throw.
throws
• If a method is capable of causing an exception that it does not handle, it must
specify this behavior so that callers of the method can guard themselves
against that exception.
• You do this by including a throws clause in the method’s declaration. A throws
clause lists the types of exceptions that a method might throw.
• This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list


{
// body of method
}
// Throws
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
finally
The finally clause is written with the try-catch statement. It is guaranteed to be executed after a catch block or
before the method quits.
Syntax
try
{
// statements
}
catch (<exception> obj)
{
// statements
}
finally
{
//statements
}
class Finally_Block class Main
{ {
float division ( )
{
public static void main(String args[])
Try {
{ float result;
int num = 34, den = 2; Finally_Block f= new Finally_Block();
float quot = num / den; result=f.division();
return quot;
}
System.out.println (result);
catch(ArithmeticException e) }
{ }
System.out.println ("Divide by zero");
}
Finally
{ OUTPUT
System.out.println ("In the finally block"); In the finally block
}
return -1;
17.0
}
}
eptions can be categorized into two ways:
Checked Exception

Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler.

Unchecked Exceptions

The unchecked exceptions are just opposite to the checked exceptions.


The compiler will not check these exceptions at compile time.
Usually, it occurs when the user provides bad data during the interaction with the program.
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.


Exception Description
Arithmetic error, such as
ArithmeticException divide-by-zero.

ArrayIndexOutOfBoundsException Array index is out-of-bounds.

Assignment to an array element of an


ArrayStoreException incompatible type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a method.

Illegal monitor operation,


such as waiting on an
IllegalMonitorStateException unlocked thread.

Environment or application is in incorrect state


IllegalStateException
Exception Description

Requested operation not compatible with current


thread state.
IllegalThreadStateException
IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a numeric format

SecurityException
Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of a string


UnsupportedOperationException An unsupported operation was encountered.
Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description

ClassNotFoundException Class not found.

CloneNotSupportedException Access to a class is denied

IllegalAccessException IllegalAccessException

Attempt to create an object of abstract class or interface


InstantiationException

InterruptedException One thread has been interrupted by another thread.

NoSuchFieldException
A requested field does not exist.

NoSuchMethodException A requested method does not exist.


Creating your own Exception Subclasses

Here you can also define your own exception classes by extending Exception. These
exception can represents specific runtime condition of course you will have to throw them
yourself, but once thrown they will behave just like ordinary exceptions.

You might also like