0% found this document useful (0 votes)
82 views55 pages

Packages and Interfaces

Packages are used to organize classes and provide access control. They act as namespaces and can control the visibility of classes, methods, and variables. Interfaces are used to define behaviors and allow for polymorphism by specifying methods without implementation, allowing multiple classes to implement the interface. Packages and interfaces provide mechanisms for compartmentalizing code and promoting code reuse through abstraction.

Uploaded by

Aditya Nath
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views55 pages

Packages and Interfaces

Packages are used to organize classes and provide access control. They act as namespaces and can control the visibility of classes, methods, and variables. Interfaces are used to define behaviors and allow for polymorphism by specifying methods without implementation, allowing multiple classes to implement the interface. Packages and interfaces provide mechanisms for compartmentalizing code and promoting code reuse through abstraction.

Uploaded by

Aditya Nath
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 55

Packages and Interfaces

 Packages are containers for classes that are


used to keep the class name space
compartmentalized

 It provides mechanism for partitioning the


class name space into manageable chunks

 It is both a naming and visibility control


mechanism

 Packages are stored in a hierarchical manner


and are explicitly imported into new class
definitions.
 Any classes declared within that file will belong
to the specified package.
 The package statement defines a name space
in which classes are stored.
 Omitting 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;
pkg is the name of the package.
 Java uses file system directories to store packages

 Directory name must match the package name


exactly.

 More than one file can include the same package


statement.

 The package statement specifies to which package


the classes defined in a file belong. It does not
exclude other classes in other files from being part of
that same package.
 Hierarchy of packages can be obtained separating
each package name from the one above it by use of a
period.
 The general form of a multileveled package statement
package pkg1[.pkg2[.pkg3]];

 A package hierarchy must be reflected in the file


system of your Java development system
Finding Packages and CLASSPATH

 The Java run-time system uses the current


working directory as its starting point. If your
package is in the current directory, or a
subdirectory of the current directory, it will be
found.
 Specify a directory path or paths by setting
the CLASSPATH environmental variable.
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
 Compile the file. The resulting .class file should be
in the MyPack directory.

 Execute the AccountBalance class using the


command line:
java MyPack.AccountBalance

 You will have to be in the directory above MyPack


when you execute this command, or to have your
CLASSPATH environmental variable set
appropriately.
Access Protection
 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 for data and code.

 The class is Java’s smallest unit of abstraction.


 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(Different package non sub
class)
 The three access specifiers, private, public,

and protected, provide a variety of ways to


produce the many levels of access required by
these categories
 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.
 When a package is imported, only those items
within the package declared as public will be
available to non-subclasses in the importing code.

 A class has only two possible access levels:


default and public.

 When a class is declared as public, it is


accessible by any other code. If a class has default
access, then it can only be accessed by other code
within its same package
Class member access
This is file Protection.java:
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
System.out.println("base constructor");
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 Derived.java:
package p1;
class Derived extends Protection {
Derived() {
System.out.println("derived constructor");
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 SamePackage.java:
package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
This is file Protection2.java:

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 and p2.
package p1;
// Instantiate the various classes in p1.
public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
} }
The test file for p2 is shown next:
package p2;
// Instantiate the various classes in p2.
public class Demo {
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
} }
Importing Packages

 Java includes the import statement to bring certain


classes, or entire packages, into visibility.
 Once imported, a class can be referred to directly,
using only its name.
 In a Java source file, import statements occur
immediately following the package statement (if it
exists) and before any class definitions.
 The general form of the import statement:
import pkg1[.pkg2].(classname|*);
 The star form may increase compilation
time—especially if you import several
large packages.
 Explicitly name the classes that you want

to use rather than importing whole


packages.
 The star form has absolutely no effect on

the run-time performance or size of your


classes.
 java.lang, is implicitly imported by the
compiler for all programs.
 This is equivalent to the following line being at
the top of all of your programs:
import java.lang.*;
 If a class with the same name exists in two
different packages that you import using the
star form, the compiler will remain silent,
unless you try to use one of the classes.
 In that case, you will get a compile-time error
and have to explicitly name the class
specifying its package
 With import
import java.util.*;
class MyDate extends Date {
}

 Without import
class MyDate extends java.util.Date {
}
package MyPack;
/* The Balance class, its constructor, and its show()
method are public. This means that they can be used
by non-subclass code outside their package. */
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
Interfaces
 Interface 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
 Interfaces don’t make assumptions about how they
are implemented.
 Once it is defined, any number of classes can
implement an interface.
 One class can implement any number of
interfaces.

02/19/11 Smitha N Pai, CSE Dept. 27


 To implement an interface, a class must create the
complete set of methods defined by the interface.

 Each class is free to determine the details of its


own implementation.

 Providing the interface keyword, Java allows to


fully utilize the “one interface, multiple methods”
aspect of polymorphism.

02/19/11 Smitha N Pai, CSE Dept. 28


 Interfaces are designed to support dynamic
method resolution at run time.

 In order for a method to be called from one class to


another, both classes need to be present at
compile time so the Java compiler can check to
ensure that the method signatures are compatible.

02/19/11 Smitha N Pai, CSE Dept. 29


 Interfaces disconnect the definition of a method or
set of methods from the inheritance hierarchy.

 Since interfaces are in a different hierarchy from


classes, it is possible for classes that are unrelated
in terms of the class hierarchy to implement the
same interface.

 Interfaces add most of the functionality that is


required for many applications which would
normally resort to using multiple inheritance in a
language such as C++.
02/19/11 Smitha N Pai, CSE Dept. 30
Defining an Interface
An interface is defined much like a class.
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;
}
 name is the name of the interface, and can be any valid identifier.
 The methods which are declared have no bodies.
 They end with a semicolon after the parameter list.
 They are abstract methods
02/19/11 Smitha N Pai, CSE Dept. 31
• 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.
• Access is either public or not used.
• When no access specifier is included, then
default access results, and the interface is only
available to other members of the package in
which it is declared.
• When it is declared as public, the interface can
be used by any other code.
02/19/11 Smitha N Pai, CSE Dept. 32
 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 with a constant value.


All methods and variables are implicitly public if
the interface, itself, is declared as public.

02/19/11 Smitha N Pai, CSE Dept. 33


Implementing Interfaces
 Once an interface has been defined, one or more
classes can implement that interface.
 To implement an interface, include the
implements clause in a class definition, and then
create the methods defined by the interface.
 The general form of a class that includes the
implements clause looks like this:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body
}
 Here, access is either public or not used.
02/19/11 Smitha N Pai, CSE Dept. 34
 If a class implements more than one interface, the
interfaces are separated with a comma.
 If a class implements two interfaces that declare
the same method, then the same method will be
used by clients of either interface.
 The methods that implement an interface must be
declared public.
 Type signature of the implementing method must
match exactly the type signature specified in the
interface definition.
 It is both permissible and common for classes that
implement interfaces to define additional members
of their own.
02/19/11 Smitha N Pai, CSE Dept. 35
Accessing Implementations Through
Interface References
 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.

02/19/11 Smitha N Pai, CSE Dept. 36


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.");
} }
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
02/19/11 Smitha N Pai, CSE Dept. 38
}}
 c can be used to access the callback( ) method,
it cannot access any other members of the Client
class.

 An interface reference variable only has


knowledge of the methods declared by its
interface declaration.

 Thus, c could not be used to access


nonIfaceMeth( ) since it is defined by Client but
not Callback.

02/19/11 Smitha N Pai, CSE Dept. 39


 Because dynamic lookup of a method at run time
incurs a significant overhead when compared with
the normal method invocation in Java, you should
be careful not to use interfaces casually in
performance-critical code.

02/19/11 Smitha N Pai, CSE Dept. 40


// Another implementation of Callback.
class AnotherClient implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("Another version of callback");
System.out.println("p squared is " + (p*p));
}}
class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42); } }
callback called with 42
Another version of callback
p squared is 1764
02/19/11 Smitha N Pai, CSE Dept. 41
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.
abstract class Incomplete implements Callback {
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
The class Incomplete does not implement callback( ) and
must be declared as abstract.
Any class that inherits Incomplete must implement callback( )
or be declared abstract itself.
02/19/11 Smitha N Pai, CSE Dept. 42
Applying Interfaces

 The interface that defines an integer stack in a file


called IntStack.java
// Define an integer stack interface.
interface IntStack {
void push(int item); // store an item
int pop(); // retrieve an item
}

02/19/11 Smitha N Pai, CSE Dept. 43


class FixedStack implements IntStack {
private int stck[];
private int tos;
// allocate and initialize stack
FixedStack(int size) {
stck = new int[size];
tos = -1;
}
public void push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

public int pop() {


if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--]; } }
02/19/11 Smitha N Pai, CSE Dept. 44
class IFTest {
public static void main(String args[]) {
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++) mystack1.push(i);
for(int i=0; i<8; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}
02/19/11 Smitha N Pai, CSE Dept. 45
// Implement a "growable" stack.
class DynStack implements IntStack {
private int stck[];
private int tos;
// allocate and initialize stack
DynStack(int size) {
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
// if stack is full, allocate a larger stack
if(tos==stck.length-1) {
int temp[] = new int[stck.length * 2]; // double size
for(int i=0; i<stck.length; i++) temp[i] = stck[i];
stck = temp;
stck[++tos] = item;
}
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];} }

02/19/11 Smitha N Pai, CSE Dept. 46


class IFTest2 {
public static void main(String args[]) {
DynStack mystack1 = new DynStack(5);
DynStack mystack2 = new DynStack(8);
// these loops cause each stack to grow
for(int i=0; i<12; i++) mystack1.push(i);
for(int i=0; i<20; i++) mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0; i<12; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<20; i++)
System.out.println(mystack2.pop());
}}
02/19/11 Smitha N Pai, CSE Dept. 47
class IFTest3 {
public static void main(String args[]) {
IntStack mystack; // create an interface reference variable
DynStack ds = new DynStack(5);
FixedStack fs = new FixedStack(8);
mystack = ds; // load dynamic stack
// push some numbers onto the stack
for(int i=0; i<12; i++) mystack.push(i);
mystack = fs; // load fixed stack
for(int i=0; i<8; i++) mystack.push(i);
mystack = ds;
System.out.println("Values in dynamic stack:");
for(int i=0; i<12; i++)
System.out.println(mystack.pop());
mystack = fs;
System.out.println("Values in fixed stack:");
for(int i=0; i<8; i++)
System.out.println(mystack.pop());
} 02/19/11 Smitha N Pai, CSE Dept. 48
 Accessing multiple implementations of an interface
through an interface reference variable is the most
powerful way that Java achieves run-time
polymorphism.

02/19/11 Smitha N Pai, CSE Dept. 49


Variables in Interfaces
 You can use interfaces to import shared constants
into multiple classes by simply declaring an
interface that contains variables which are
initialized to the desired values.
 When you include(implement) that interface in a
class all of those variable names will be in scope
as constants.
 If an interface contains no methods, then any class
that includes such an interface doesn’t actually
implement anything.
 It is as if that class were importing the constant
variables into the class name space as final
02/19/11 Smitha N Pai, CSE Dept. 50
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}

02/19/11 Smitha N Pai, CSE Dept. 51


class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 30)
return NO; // 30%
else if (prob < 60)
return YES; // 30%
else if (prob < 75)
return LATER; // 15%
else if (prob < 98)
return SOON; // 13%
else
return NEVER; // 2%
02/19/11 Smitha N Pai, CSE Dept. 52
}}
class AskMe implements SharedConstants {
static void answer(int result) {
switch(result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
02/19/11 Smitha N Pai, CSE Dept. 53
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
The results are different each time it is run.
Later
Soon
No
Yes
02/19/11 Smitha N Pai, CSE Dept. 54
Interfaces Can Be Extended
• Interface can inherit another by use of the
keyword extends.
• The syntax is the same as for inheriting
classes.
• When a class implements an interface that
inherits another interface, it must provide
implementations for all methods defined within
the interface inheritance chain.

02/19/11 Smitha N Pai, CSE Dept. 55


interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
02/19/11
ob.meth3(); } } Smitha N Pai, CSE Dept. 56

You might also like