Module 4 - UA
Module 4 - UA
}
} OUTPUT:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
• Packages are containers for classes that are used to
keep the class name space compartmentalized.
• For example, a package allows you to create a class
named List, which you can store in your own package
without concern that it will collide with some other
class named List stored elsewhere.
• Packages are stored in a hierarchical manner and are
explicitly imported into new class definitions.
• Java provides a mechanism for partitioning the class
Packages name space into more manageable chunks. This
mechanism is the package.
• The package is both a naming and a visibility control
mechanism.
• You can define classes inside a package that are not
accessible by code outside that package.
• Preventing naming conflicts.
• For example there can be two classes with name
Employee in two packages,
college.staff.cse.Employee and
college.staff.ee.Employee
• Making searching/locating and usage of classes, interfaces,
enumerations and annotations easier
Packages are • Providing controlled access: protected and default have
package level access control.
used for, • A protected member is accessible by classes in the same
package and its subclasses. A default member (without any
access specifier) is accessible by classes in the same package
only.
• Packages can be considered as data encapsulation (or data-
hiding).
• Include a package command as the first statement in a Java
source file.
• Any classes declared within that file will belong to the specified
package.
• 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.
• Syntax: package pkg;
Here, pkg is the name of the package.
package MyPackage;
• 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.
• 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 pkg1[.pkg2[.pkg3]];
Package package java.awt.image;
• needs to be stored in java\awt\image in a
Windows environment.
Two types
1. Built-in Packages
java.lang: Contains language support classes
Types of java.io: Contains classed for supporting input /
packages output operations.
java.applet: Contains classes for creating
Applets.
2. User-defined packages
These are the packages that are defined by the
user.
• How does the Java run-time system know where to
look for packages that you create?
• The answer has three parts.
• First, by default, the Java run-time system uses the
Finding current working directory as its starting point. Thus,
if your package is in a subdirectory of the current
Packages and directory, it will be found.
CLASSPATH • Second, you can specify a directory path or paths
by setting the CLASSPATH environmental variable.
• Third, you can use the -classpath option with
java and javac to specify the path to your classes.
• When the second two options are used, the
class path must not include MyPack, itself.
• It must simply specify the path to MyPack.
Finding • For example, in a Windows environment, if the
Packages and path to MyPack is
CLASSPATH
C:\MyPrograms\Java\MyPack
• Then the class path to MyPack is
C:\MyPrograms\Java
• Classes and packages are both means of
encapsulating and containing the name space and
scope of variables and methods.
• Packages act as containers for classes and other
subordinate packages.
• Classes act as containers
Access • Java addresses four categories of visibility for class
Protection 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
for data and code.
Same Different
Same Difference
Access package package
Same class package Package
Modifier non- non-
subclass subclass
subclass subclass
Private Yes No No No No
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
Output:Hello
//save by A.java package
pack; public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
fully qualified
name class B{
public static void main(String args[]){
pack.A obj = new pack.A(); // using fully qualified name
obj.msg();
}
}
OUTPUT:Hello
fully qualified name
import java.util.*;
class MyDate extends Date {
}
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set
classpath of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
e:\sources> java -classpath c:\classes mypack.Simple
Ways to load the class files or jar files
The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.
The relationship between classes and
interfaces
}
class IntfEx implements printable{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[]){
IntfEx obj = new IntfEx();
obj.print();
}
}
Accessing Implementations Through Interface
References
• You can declare variables as object references that use an interface
rather than a class type.
• Any instance of any class that implements the declared interface can
be referred to by such a variable. When you call a method through
one of these references, the correct version will be called based on
the actual instance of the interface being referred to. This is one of
the key features of interfaces.
• The method to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which calls
methods on them. The calling code can dispatch through an
interface without having to know anything about the “callee.”
• This process is similar to using a superclass reference to access a
subclass object.
interface Drawable{
void draw();
Output:
} drawing circle
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable{
public void draw(){
System.out.println("drawing circle");
}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}
interface Bank{
float rateOfInterest(); Output:
} ROI: 9.15
class SBI implements Bank{
public float rateOfInterest(){
return 9.15f;
}
}
class PNB implements Bank{
public float rateOfInterest(){
return 9.7f;
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Multiple inheritance in Java by interface
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){
System.out.println("Hello nested interface");
}
Output:
hello nested interface
Applying Interfaces
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Error Message:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
• When the Java run-time system detects the attempt to divide by zero, it
constructs a new exception object and then throws this exception.
• This causes the execution of Exc0 to stop, because once an exception has
been thrown, it must be caught by an exception handler and dealt with
immediately.
• In this example, haven’t supplied any exception handlers, so the
exception is caught by the default handler provided by the Java run-
time system.
• Any exception that is not caught by your program will ultimately be
processed by the default handler.
• The default handler displays a string describing the exception, prints a
stack trace from the point at which the exception occurred, and
terminates the program.
stack trace
The stack trace will always show the sequence of method invocations
that led up to the error.
The stack trace contains all invocations from the start of a thread until
the point it's generated. This is usually a position at which an exception
takes place. For example:
class Exc1 {
static void subroutine() { int d = 0; The resulting stack trace from the default exception
handler:
int a = 10 / d;
} java.lang.ArithmeticException: / by zero at
public static void main(String args[]) { Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
Exc1.subroutine();
}
}
Using try and catch
• Handle an exception
– First, it allows you to fix the error.
– Second, it prevents the program from
automatically terminating.
• 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 {
11block of code to monitor for errors
}
catch (ExceptionTypel el ) {
II exception handler for Exception'J'ypel
}
catch (ExceptionType2 e2) {
II exception handler for Exception1'ype2
}
II ..•
finally {
II block of code to be executed before try block
ends
}
package examplejava;
catch(NullPointerException e) {
System.out.println("Caught inside
demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
This program gets two chances to deal with the same
error.
First, main( ) sets up an exception context and then calls
demoproc( ).
The demoproc( ) method then sets up another exception handling
context and immediately throws a new instance of
NullPointerException, which is caught on the next line.
The exception is then rethrown.
output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
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.
• All other exceptions that a method can throw must be declared in
the throws clause.
• If they are not, a compile-time error will result.
type method-name(parameter-list) throws exception-list
{
// body of method
}
• Here, exception-list is a comma-separated list of the exceptions that a method can
throw.