WT Lecture-6 (Interface & Packages)
WT Lecture-6 (Interface & Packages)
4 10/14/23
Defining an Interface
• Defining an interface is similar to creating a new class.
• An interface definition has two components: the interface
declaration and the interface body.
interfaceDeclaration
{
interfaceBody
}
The interfaceDeclaration declares various attributes
about the interface such as its name and whether it
extends another interface.
The interfaceBody contains the constant and method
declarations within the interface
5 10/14/23
public interface StockWatcher
{
final String sunTicker = "SUNW";
final String oracleTicker = "ORCL";
final String ciscoTicker = "CSCO";
void valueChanged
(String tickerSymbol,
double newValue);
}
6 10/14/23
Implementing an Interface
Include an implements clause in the class declaration.
8 10/14/23
public class StockMonitor
implements StockWatcher
{
...
public void valueChanged
(String tickerSymbol, double newValue)
{
if (tickerSymbol.equals(sunTicker))
{ ... }
else if
(tickerSymbol.equals(oracleTicker))
{ ... }
else if (tickerSymbol.equals(ciscoTicker))
{ ... }
}
}
9 10/14/23
Properties of Interface
A new interface is a new reference data type.
Interfaces are not instantiated with new, but they have
certain properties similar to ordinary classes
You can declare that an object variable will be of that
interface type
e.g.
Comparable x = new Tile(…);
Tile y = new Tile(…);
if (x.compareTo(y) < 0) …
10 10/14/23
Superinterface (1)
An interface can extend other interfaces, just as a
class can extend or subclass another class.
An interface can extend any number of interfaces.
The list of superinterfaces is a comma-separated
list of all the interfaces extended by the new
interface
public interfaceName
Extends superInterfaces
{
InterfaceBody
}
11 10/14/23
Superinterface (2)
Two ways of extending interfaces:
Add new methods
Define new constants
12 10/14/23
Interfaces Cannot Grow!
Add some functionality to StockWatcher?
public interface StockWatcher
{
final String sunTicker = "SUNW";
final String oracleTicker = "ORCL"; final
String ciscoTicker = "CSCO";
void valueChanged(String tickerSymbol,
double newValue);
void currentValue(String tickerSymbol,
double newValue);
}
If you make this change, all classes that implement
the old interface will break because they don’t
implement the interface anymore!
13 10/14/23
Try to anticipate all uses for your interface up
front and specify it completely from the beginning.
Create a StockWatcher subinterface called
StockTracker that declared the new method:
public interface StockTracker
extends StockWatcher
{
void currentValue(String tickerSymbol,
double newValue);
}
Users can choose to upgrade to the new interface
or to stick with the old interface.
14 10/14/23
Multiple Inheritance
Person
Student Employee
TeachingAssistant
15 10/14/23
class TeachingAssistant extends Student
{
private EmployeeAttributes ea;
…
public String getEmployeeID()
{
return this.ea.getEmployeeID();
}
}
16 10/14/23
Interface Comparable
{
int compareTo(Object o);
}
17 10/14/23
What is in interface Z ?
interface x
{
char A = ‘A’;
void gogi();
}
interface Y
{
char B = ‘B’;
}
interface Z extends X, Y
{
void dogi();
}
18 10/14/23
Name conflicts in extending interfaces
A class automatically implements all interfaces
that are implemented by its superclass.
Interfaces belong to Java namespace and as such
are placed into packages just like classes.
Some interfaces are declared with entirely empty
bodies. They serve as labels for classes:
The most common marker interfaces are Cloneable and
Serializable
class Car implement Cloneable
{…
public Object clone()
{ return super.clone();
}
}
19 10/14/23
interface X
{ char A = ‘A’; class C implements Z
void gogi(); { public void gogi()
void dogi(); { char c = Y.A; …
} }
interface Y public void dogi()
{ char A = ‘B’; { char c = X.A; …
void gogi(); //but not int gogi() }
} public void dogi(int i)
interface Z extends X, Y { …
{ this.dogi(i – 1);
void dogi(int i); }
} }
20 10/14/23
Interface and Callbacks
Suppose you want to implement a Timer class. You
want your program to be able to:
Start the timer;
Have the timer measure some time delay
Then carry out some action when the correct time has
elapsed.
21 10/14/23
class Timer extends Thread
{
…
public void run()
{
while (true)
{
sleep(delay);
//now what?
}
}
}
The object constructing a Timer object must somehow tell the timer.
What to do when the time is up?
interface TimerListener
{
public void timeElapsed(Timer t);
22
} 10/14/23
class Timer extends Thread class AlarmClock implements
TimerListener
{
{ AlarmClock()
Timer(TimerListener t) { listener =
t;} {
… Timer t = new Timer(this);
public void run() t.setDelay(1000);
{ while (true) //1000 milliseconds
{ }
sleep(interval); public void timeElapsed(Timer t)
{
listener.timeElapsed(this); if (t.getTime() >= wakeUpTime)
} wakeUp.play();
TimerListener listener; }
} }
}
23 10/14/23
What is Package?
A package is a collection of related classes and
To control access
24 10/14/23
Why Using Packages?
Programmers can easily determine that these
classes and interfaces are related.
Programmers know where to find classes and
interfaces that provide graphics-related functions.
The names of classes won’t conflict with class
names in other packages, because the package
creates a new namespace.
Allow classes within the package to have
unrestricted access to one another yet still restrict
access for classes outside the package
25 10/14/23
Put Your Classes and Interfaces into Packages
It is no need to “create” packages, they come to
existence as soon as they are declared
The first line of your source file:
package <package_name>;
e.g. package cars;
class Car
{…}
Every class must belong to one package.
Only one package statement is allowed per source
file.
If package statement is omitted, the class belongs to
a special default package – the only package in Java
that has no name.
26 10/14/23
Subpackages
We can create hierarchies of nested packages
e.g.
package machines.vehicles.cars;
class FastCar extends Car
{…}
Subpackage names must always be prefixed with
names of all enclosing packages.
Package hierarchy does not have a single top-level
all-encompassing root package.Instead, we deal
with a collection of top-level packages
27 10/14/23
Partial Package Tree of Java
java
lang
String
Math
reflect
Constructor
Method
awt
Frame
Button
io
ObjectInputStream
ObjectOutputStream
util
Vector
Random
28 10/14/23
Packages and Class
Packages subdivide name space of Java classes
machines.vehicles.cars.FastCar mycar =
new machine.vehicles.cars.FastCar();
Package names should be made as unique as
possible to prevent name clashes
Class name must be fully qualified with their
package name. Except:
Class name immediately following the class keyword,
e.g. class Car{…}
Class belongs to the same package as the class being
currently defined
Class is explicitly specified in one of the import
statements
Class belongs to java.lang package (all java.lang classes
29
are implicitly imported) 10/14/23
import Statement
To avoid typing fully qualified names – use import
statements sandwiched between the package statement
and class definition.
e.g. package grand.prix;
import java.lang.*; //implicitly specified
import java.util.Random;
import machines.vehicles.cars.*;
import machines.*.*; //COMPILER ERROR!
import Racer; //from default package
30 10/14/23
Store Class Files
Class files must be stored in a directory structure that
mirrors package hierarchy
e.g. Both .java and .class files for FastCar class from the
machines.vehicles.cars package can be stored in the
following directory:
C:\A\B\classes\machines\vehicles\cars
31 10/14/23
Classpath
Compiled classes can be stored in different locations in
the file systems.
How to locating these files – Setting a classpath which
is a list of directories where class files should be
searched
e.g. If Java system is to find classes from the
machines.vehicles.cars package , its classpath must point
to C:\A\B\classes, the root of the package directory
hierarchy.
32 10/14/23
Setup Classpath
In command line
c:\> java –classpath C:\A\B\classes machines.vehicles.cars.Car
To avoid specify the classpath in every command, set
classpath as a command shell environment variable:
Windows:
>set CLASSPATH = C:\A\B\classes
>set CLASSPATH = .; %CLASSPATH%
>echo %CLASSPATH%
.; C:\A\B\classes
Unix:
$CLASSPATH = $HOME/A/B/classes
$CLASSPATH = .: $CLASSPATH
$echo $CLASSPATH
.: home/santa/A/B/classes
33 10/14/23
Classpath for .zip and .jar File
JDK can open .zip and .jar archives and search for
class files inside.
The archives must store class files within the
appropriate directory structure.
Set up classpath for archives:
>set CLASSPATH = %CLASSPATH%;c:\user.jar
34 10/14/23
Exercise
1. What methods would a class that implements the
java.util.Iterator interface have to implement?
2. What is wrong with the following interface?
public interface SomethingIsWrong {
public void aMethod(int aValue)
{
System.out.println("Hi Mom");
}
}
3. Fix the interface in question 2.
4. Is the following interface valid?
public interface Marker { }
35 10/14/23
5. Write a class that implements the Iterator interface
found in the java.util package. The ordered data for
this exercise is the 13 cards in a suit from a deck of
cards. The first call to next returns 2, the subsequent
call returns the next highest card, 3, and so on, up to
Ace. Write a small main method to test your class.
36 10/14/23