Package&interface 9 B
Package&interface 9 B
Package&interface 9 B
means of classes
organizing classes
together as Package
groups.
Features of Packages
Packages are useful for the following purposes: Packages allow you to
organize your classes into smaller units ( such as folders ) and make it easy
to locate and use the appropriate class file.
It helps to avoid naming conflicts. When you are working with a number of
classes, it becomes difficult to decide on names of the classes & methods.
At times you would want to use the same name, which belongs to an
another class. Package, basically hides the classes and avoids conflicts in
names.
Packages allow you to protect your classes, data and methods in a larger
way than on a class-to-class basis.
Package names can be used to identify your classes.
Packages in Java
• Code reusability is the main philosophy of
Object Oriented Programming
• To power this advantage, Java has a number
of packages called API bundled with the JDK
• Packages are collection of classes and
interfaces to facilitate a number of ready
made solutions
• A great knowledge of packages helps the Java
developer to master in Java solution
• In addition to the API, user can maintain their
own packages
API – The Built-in Java Packages
API
W in d o w T o o lK it
C o re P a c k a g e s a n d A p p le t
ja v a . la n g ja v a . io ja v a . u t il ja v a . n e t ja v a . a w t ja v a . a w t . im a g e ja v a . a w t . p e e r ja v a . a p p le t
Using API Packages
• A package is a collection of classes and each class is a
collection of members and methods.
• Any class as well as any member and method in a package
are accessible from a Java program
• This can be achieved in Java by import statement
• There are two ways of using import statement
– With fully quantified class name
• When it is required to access a particular class
Example: java.lang.String
– With default (.*) quantification
• When it is required to access a number of classes
Example: java.lang.*
Using API Packages
Package Circle
Class
Method to find
Some Some
area of the circle
Method Method
Import
To find the area of a circle on the front
face of the cube, we need not write a
code explicitly to find the area of the
circle
We will import the package into our
program and make use of the area
method already present in the package
Importing a Package
In Java, the Packages (where the required method is already created) can be
imported into any program where the method is to be used.
We can import a Package in the following manner :
import package_name . class_name ;
Suppose you wish to use a class say My_Class whose location is as follows :
mypackage
Compiling the package
javac
javac-d-d c:\
c:\JavaProgs
JavaProgsCalculate.java
Calculate.java
• package MyPackage;
• public class MyClass {
• public void test ( ) {
• System.out.println ( " Welcome to My
Class !");
• }
• }
• // Import the package with the following code.
• import MyPackage.MyClass;
• class PackageTestAppln {
• public static void main ( String args [ ] ) {
• MyClass theClass = new MyClass ( );
• theClass.test ( );
• }
• }
User Defined Packages: Example
Jav a w o rk in g d ire c to ry
. P a c k a g e T e s tA p p ln .c la s s
. M yPackage P a c k a g e d ire c to ry
. M y C la s s .ja v a
. M y C la s s .c la s s
• Note
– We cannot put two or more public classes together in a
.java file; otherwise there will be an ambiguitu in naming
the .java file
• package P
• public class B {
• ...
• }
• Steps
1.Create a directory named P
2.Store the class A in the file A.java in it
3.Comiple A.java and place it in the directory P
4.Store the class B in the file B.java in it
5.Comiple B.java and place it in the directory P.
Standard Java Packages
The Three Java Packages that are essential to any Java program are :
java .lang
java
java. .lang
lang Contains classes that form the basis of the
design of the programming language of Java
java
java. .ioio
java .io
java
java. .util
util The use of streams for all input output
operations in Java is handled by the java.io
package
java . util
Contains classes and interfaces that provide additional utility but may not be
always vital.
java.lang package
One of the most important classes defined in this package is Object and
it represents the root of the java class hierarchy.
This package also holds the “wrapper” classes such as Boolean,
Characters, Integer, Long, Float and Double.
Many a times it is necessary to treat the non-object primitive datatypes
of int, char, etc. as objects.
Thus Java defines “wrapper” classes that enable us to treat even
primitive data types as objects.These wrapper classes are found in the
package “java.lang”.
Other classes found in this package are :
Math – which provides commonly used mathematical functions like
sine, cosine and square root.
String & String Buffer – Encapsulate commonly used operations on
character strings.
Some of the important methods of Math
class
• intabs(int i) -- returns the absolute value of i
•long abs(long l) -- returns the absolute value
of l
•float abs(float f) -- returns the absolute value
of f
•double abs(double d) -- returns the
absolute value of d
•double ceil(double d) -- returns as a double
the smallest integer that is not less than d
• double floor(double d) --- returns as a
double the largest integer
java.io package
Since these are abstract classes, they cannot be used directly but must be
inherited, so that the abstract methods can be implemented.
All I/O stream classes are derived from either of these classes.
java.io package
The classes derived in Inputstream and Outputstream can only read from or write to
the respective files.
We cannot use the same class for both reading and writing operations.
An exception to this rule is the class “RandomAccessFile”.
This is the class used to handle files that allow random access and is capable of mixed
reading and writing operations on a file.
There are two additional interface to this package :
• Data input
• Data output
•These classes are used to transfer data other than bytes or characters
Java.util package
One of the most important package in this package is the class “Date”, which can be
used to represent or manipulate date and time information.
In addition, the class also enable us to account for time zones .
Java helps us to change the size of an array which is usually fixed, by making use of
the class “Vector”. This class also enable us to add, remove and search for items in
the array.
Tips on using packages
The statement :
import java.awt.* ;
Will include all the classes available in the “awt” subdirectory present in
the java directory.
While creating a package, care should be taken that the statement for
creating a package must be written before any other import statements
LEGAL ILLEGAL
java.net
Interface
Interface in Java
• Java does not support multiple inheritance
as C++ supports
• Java supports an alternative approach to
this OOP feature known as interface
• What is Interface?
– An interface is basically a kind of class. Like
classes, an interface contains members and
methods;
Defining 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;
}
• interface Callback {
• void callback(int param);
• }
Implementing Interfaces
• access class classname [extends superclass]
• [implements interface [,interface...]] {
• // class-body
• }
• class TestIface {
• public static void main(String args[]) {
• Callback c = new Client();
• c.callback(42);
• }
• }
Defining an Interface: Examples
• Example 1
interface anItem
{
static final int code = 101;
static final String itemName = “Computer”
void recordEntry( );
}
• Example 2
interface curves extends circle, ellipse
{
static final float pi = 3.142F;
float area(int a, int b);
void print( );
}
Implementation of classes with Interface
• Syntax
l
r n
w
m
G e o A n a ly z e r
. pi
. a re a ( )
. p e rim e te r()
Implementation of classes with Interface Ex.
(contd..)
• interface GeoAnalyzer
• {
• final static float pi = 3.142F;
• float area( );
• float perimeter( );
• }
Implementation of classes with Interface Ex. (contd..)
• Ellipse(float m, flaot n) {
• major = m;
• minor = n; }
• Rectangle(float l, float w) {
• length = l; width = w; }
• class Geometry {
• static void display(float x, float y) {
System.out.println("Area = " + x + "Perimeter = " + y);
• }
• public static void main(String args[ ]) {
• Circle c = new Circle(5.2);
• Ellipse e = new Ellipse(4.5, 3.6);
• Rectangle r = new Rectangle(6.5, 4.3);
• GeoAnalyzer geoItem;
• geoItem = c;
• display(geoItem.area(), geoItem.perimeter());
• geoItem = e;
• display(geoItem.area(), geoItem.perimeter());
• geoItem = r;
• display(geoItem.area(), geoItem.perimeter());
• } }
• interface P { • interface P12 extends P1, P2
• int p = 0; {
• void fp(); } • int p12 = 12;
• void fp12(); }
• interface P1 extends P { • class Q implements P12 {
• int p1 = 1; • public void fp() {
• void fp1(); } System.out.println("fp: " + p);
• }
• interface P2 extends P { • public void fp1() {
• int p2 = 2; System.out.println("fp1: " + p1);
• void fp2(); } • }
• public void fp2() { • class
• System.out.println("fp InheritanceExample {
2: " + p2); • public static void
• } main(String args[]) {
• public void fp12() { • Q q = new Q();
• • q.fp();
System.out.println("fp • q.fp1();
12: " + p12); • q.fp2();
• } • q.fp12();
• } • }}
Implementation of classes with Interface
Example (contd..)
c la s s E m p lo y e e
. ...
. ...
. ...
c la s s T e a c h e r c la s s S tu d e n t
. ... . ...
. ... . ...
. m e m b e r P r o f ile ( ) . m e m b e r P r o file ()
m e m b e r IE E E
. m e m b e r S h ip Y e a r
. r e g io n IE E E
. m e m b e r P r o file ()
Extending Interface
• Interface can inherit from other interface
• Interface can also multiply inherits
• interface Constants {
• double velOfLight = 3.0e+10;
• String unitVelOfLight = "m/s";
• .... .... .... ....
• }
• interface Physics {
• void quantumLaw();
• ... ... ... ...
• }
Extending Interface
• interface Chemistry extends Constants
• {
• ..... ..... ...... .....
• ..... ..... ...... .....
• }