Professional Documents
Culture Documents
Java Unit - 1 - Part - 2
Java Unit - 1 - Part - 2
Unit - 1
Packages
Packages are containers for classes.
They are used to keep the class name space
compartmentalized.
You also need some way to be assured that the
name you choose for a class will be reasonably
unique and not collide with class names chosen
by other programmers.
The package is both a naming and a visibility
control mechanism.
Defining a Package
To create a package is quite easy: simply
include a package command as the first
statement in a Java source file.
The package statement defines a name space
in which classes are stored.
If you omit the package statement, the class
names are put into the default package, which
has no name.
This is the general form of the package
statement: package pkg;
Defining a Package
Java uses file system directories to store
packages.
For example, the .class files for any classes you
declare to be part of MyPackage must be
stored in a directory called MyPackage.
More than one file can include the same
package statement. The package statement
simply specifies to which package the classes
defined in a file belong.
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.
Defining a Package
The general form of a multileveled package
statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the
file system of your Java development system.
For example, a package declared as package
java.awt.image; needs to be stored in
java\awt\image in a Windows environment.
Access Protection
Java addresses four categories of visibility for
class members:
Subclasses in the same package
Non-subclasses in the same package
Subclasses in different packages
Classes that are neither in the same package
nor subclasses
The three access modifiers, private, public, and
protected, provide a variety of ways to produce
the many levels of access required by these
categories.
Access Protection
Anything declared public can be accessed
from anywhere.
Anything declared private cannot be seen
outside of its class.
When a member does not have an explicit
access specification, it is visible to subclasses as
well as to other classes in the same package.
This is the default access.
If you want to allow an element to be seen
outside your current package, but only to
classes that subclass your class directly, then
declare that element protected.
Access Protection
Package Example
Package Example
Package Example
Call
this file Balance.java and put it in a
directory called MyPack.
Next, compile the file.
Make sure that the resulting .class file is
also in the MyPack directory.
Compile and Run TestBalance.java file.
javac TestBalance.java
java TestBalance
Interfaces
It is used to define role of an entity.
“interface” keyword is used for the interfaces.
By using interfaces we can implement the
concept of multiple inheritances in JAVA.
Interface is by default “abstract” i.e. all the
methods present in the interface are by default
“public nonstatic and abstract”.
All the variables present in the interface are by
default “public static and final”.
“implements” keyword is used for implementing
interfaces to the class.
Defining an Interface
An interface is defined much like a class. This is a
simplified general form of an interface:
catch:
It is a method which is used to catch the
Exception arises in the try block and which is
thrown by Java Runtime Environment(JRE).
Exception Handling Mechanism
throw:
Tomanually throw an exception, use the
keyword throw.
throws:
Any exception that is thrown out of a method
must be specified as such by a throws clause.
finally:
Any code that absolutely must be executed
after a try block completes is put in a finally
block.
Exception Handling Mechanism
Note:
1. try must be followed by catch
2. try & catch must be perfect pairs.
3. A try can be followed by multiple catches.
Exception Handling Mechanism
Multiple Catch Statements
Exception Handling Mechanism
When you use multiple catch statements,
exception subclasses must come before any of
their super classes.
This is because a catch statement that uses a
superclass will catch exceptions of that type
plus any of its subclasses.
Thus, a subclass would never be reached if it
came after its superclass.
In Java, unreachable code is an error.
Exception Handling Mechanism
Nested try Statements
Nested try Statements
Throw
Normally JRE will identify the Exception and
throw the Exception but as a developer if you
want to throw manually you have to use :throw”
or “throws”.
“throw” is to throw Exception manually in the
“body level”,
General form:
throw ThrowableInstance;
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 necessary for all exceptions, except those
of type Error or RuntimeException, or any of their
subclasses.
Throws
finally
When exceptions are thrown, execution in a
method takes a rather abrupt, nonlinear path
that alters the normal flow through the method.
This could be a problem in some methods.
For example, if a method opens a file upon
entry and closes it upon exit, then you will not
want the code that closes the file to be
bypassed by the exception-handling
mechanism.
The finally keyword is designed to address this
contingency.
finally
finally creates a block of code that will be
executed after a try /catch block has
completed and before the code following the
try/catch block.
The finally block will execute whether or not an
exception is thrown.
If an exception is thrown, the finally block will
execute even if no catch statement matches
the exception.
Any time a method is about to return to the
caller from inside a try/catch block, via an
uncaught exception or an explicit return
statement, the finally clause is also executed.
finally
finally
Java’s Built-in Exceptions
Java defines several exception classes inside
the standard package java.lang.
Unchecked exception or RuntimeException
need not be included in the method’s
throws list.
Compiler does not check to see if a method
handles or throws these exceptions.
Checked exception must be included in the
method’s throws list, if that method can
generate one of these exceptions and does
not handle it itself.
Java’s Unchecked RuntimeException
Subclasses Defined in java.lang
Java’s Checked Exceptions
Defined in java.lang
Creating Your Own
Exception Subclasses
Java’s built-in exceptions handle most
common errors.
You need to create your own exception
types to handle situations specific to the
applications.
Define a subclass of Exception.
Your subclasses don’t need to actually
implement anything.
The Exception class does not define any
methods of its own.
It inherits those methods from Throwable.
Creating Your Own
Exception Subclasses
Exception defines four public constructors.
Exception(): This creates an exception that
has no description.
Exception(String msg): This form lets you
specify a description of the exception.
Exception(Throwable cause): Constructs a
new exception with the specified cause and
a detailed message.
Exception(String message, Throwable cause):
Constructs a new exception with the
specified detail message and cause.
Creating Your Own
Exception Subclasses
Creating Your Own
Exception Subclasses
Custom Exception Example
Custom Exception Example
Chained Exception
The chained exception feature allows you to
associate another exception with an
exception.
This second exception describes the cause
of the first exception
For example, imagine a situation in which a
method throws an ArithmeticException
because of an attempt to divide by zero.
However, the actual cause of the problem
was that an I/O error occurred, which
caused the divisor to be set improperly.
Chained Exception
Although the method must certainly throw an
ArithmeticException, since that is the error that
occurred, you might also want to let the calling
code know that the underlying cause was an
I/O error.
To allow chained exceptions, two constructors
and two methods were added to Throwable.
Throwable(Throwable causeExc): causeExc is
the exception that causes the current
exception.
Throwable(String msg, Throwable causeExc):
Specify a description at the same time that
you specify a cause exception.
Chained Exception
The chained exception methods supported
by Throwable are getCause() & initCause().