Package&interface 9 B

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 50

Package in Java

Why use Packages ?

Just think of Writing the


code from the scratch,
each time you create an
application

You’ll end up spending your


precious time and energy
and finally land up with a
Huge code accumulated
before you.
Reusing The Existing Code
Reusability of code is one of
the most important
requirements in the software
industry.
Reusability saves time, effort
and also ensures
consistency.
A class once developed
can be reused by any
number of programs
wishing to incorporate
the class in that
particular program.
Concept of Packages

In Java, the codes which can be reused by other


programs is put into a “Package”.
A Package is a collection of classes, interfaces
and/or other packages.
Packages are interfaces
essentially a packages

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

• However, instead of importing whole


package or a class it is possible to refer a
class in order to instantiate an object
• Example
java.util.Date toDay = new java.util.Date ( );
System.out.println(toDay);
• The same thing but with import statement
can be done as follows
import java.util.Date;
Date today = new Date( );
System.out.println(toDay);
An Example on the use of 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 :

This class can be imported as follows :


import My_Package . MySub_Package . My_Class ;
My_Package My_Sub_Package My_Class
Creating a Package

In Java Packages are created in the package


packagemypackage
mypackage; ;
following manner : public
publicclass
classcalculate
calculate
Package package_name ; {{
public
publicint
intadd(int
add(intx,x,int
inty)y)
{{
return(
return(xx++yy)); ;
Method to
}}
add( )
}}

mypackage
Compiling the package

javac
javac-d-d c:\
c:\JavaProgs
JavaProgsCalculate.java
Calculate.java

When the above command


is executed on the
command prompt, the
compiler creates a folder
s
JavaProg t e . Cla
ss called “mypackage” in our
c ula JavaProgs directory and
Cal
stores the “Calculate.class”
k ag e
mypac into this folder
User Defined Packages

• User can maintain their own package. The


package statement can be used for the
purpose with the following syntax
package myPackage
public Class myClass {
. . .
. . .
}
Here, myPackage is the name of the package and it
contains the only class myClass
User Defined Packages (contd..)

• In addition to this following steps must be


taken into consideration
1. Use package statement at the beginning of the
package file
2. Define the class that is to be put in the package and
declare it as public
3. Create a subdirectory under the working directory
with the same name as the package name
4. Store the file with the same name as the
className.java in the subdirectory created
5. Store the compile version (i.e. .class) file into the
same subdirectory
User Defined Packages: Example

• // User defined package

• 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

? How a package then contains multiple classes


• Solution
• package P
• public class A {
• ...
• }

• 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

This package has two very important abstract classes :


Input Stream – This class defines the basic behavior required for input.
Output stream – This class is the basis of all the classes that deal with output
operations in Java.

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

package mypackage ; import java . io;


import java . io; package mypackage ;
Important Packages in Java
java.lang You don’t need to explicitly import this package. It is always
imported for you.
This package consists of classes that help you for all the Input and
java.io Output operations.
This package consists of classes that you need, to execute an applet
in the browser or an appletviewer.
java.applet
This package is useful to create GUI applications.
This package provides a variety of classes and interfaces for creating
lists, calendar, date, etc.
java.awt
This package provides classes and interfaces for TCP/IP network
programming.
java.util

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 Client implements Callback {


• // Implement Callback's interface
• public void callback(int p) {
• System.out.println("callback called with " + p);
• }
• }
When you implement an interface method, it must be declared as public.
Implementing Interfaces
• It is both permissible and common for classes that implement interfaces to
define additional members of their own.
• For example, the following version of Client implements callback( ) and adds
the method nonIfaceMeth( ):

• 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
• 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.

• 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

class className [extends superClassName]

[implements interfaceName1, interfaceName2, ...]


{
Class body
}
Implementation of classes with Interface
Example

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..)

class Circle implements GeoAnalyzer


{
float radius;
Circle(float r) {
radius = r; }

public float area( ) {


return(pi*radius*radius); }

public float perimeter( ) {


return(2*pi*radius);
} }
Implementation of classes with Interface Ex. (contd..)

• class Ellipse implements GeoAnalyzer


• { float major;
• float minor;

• Ellipse(float m, flaot n) {
• major = m;
• minor = n; }

• public float area( ) {


• return(pi*major*minor); }

• public float perimeter( ) {


• return(pi*(major+minor); }}
Implementation of classes with Interface Ex. (contd..)

• class Rectangle implements GeoAnalyzer


• { float length;
• float width;

• Rectangle(float l, float w) {
• length = l; width = w; }

• public float area() {


• return(length*width); }

• public float perimeter( ) {


• return(2*(length+width)); }}
Implementation of classes with Interface Ex. (contd..)

• 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
• {
• ..... ..... ...... .....
• ..... ..... ...... .....
• }

• interface lawOfPysics extends Constants, Physics


• {
• ..... ..... ...... .....
• ..... ..... ...... .....
• }
• class A {
• public interface NestedIf {
• boolean isnotnegative(int x);
• }
• }
• class B implements A.NestedIf{
• public boolean isnotnegative(int x){
• return x<0 ? false:true;
• } }
• class NestedIfDemo {
• public static void main (String args[]) {
• A.NestedIf nif = new B();
• if (nif.isnotnegative(10))
• System.out.println("this will be displayed");
• if (nif.isnotnegative(-12))
• System.out.println("this wont be
displayed");
• }}

You might also like