Transcript Chapter 4

Programming With Java
ICS201
Chapter 13
Interfaces and Inner
Classes
1
Programming With Java
ICS201
Interface
o An interface is something like an extreme case of an
abstract class
 However, an interface is not a class
 It is a type that can be satisfied by any class that
implements the interface
o The syntax for defining an interface is similar to that of
defining a class
 Except the word interface is used in place of class
2
Programming With Java
ICS201
Interface
o An interface specifies a set of methods that any class
that implements the interface must have
 It contains method headings and constant definitions
only
 It
contains
neither
instance
variables
nor
any
complete method definitions
Example:
interface A
{
public void display( String s);
}
3
Programming With Java
ICS201
Interface
o Interface variable is implicitly public, static and final
o Interface method is implicitly public and abstract (is not
implemented by this class)
o A class can implement one or more interfaces
o An interface can be implemented by several classes
o Interface name can be used as the type of a variable i.e
interface reference
4
Programming With Java
ICS201
Interface
o An interface and all of its method headings should be
declared public
 They cannot be given private, protected, or package
access
o When a class implements an interface, it must make all
the methods in the interface public
o Because an interface is a type, a method may be
written with a parameter of an interface type
 That parameter will accept as an argument any class
that implements the interface
5
Programming With Java
ICS201
Example (Interface)
interface Communicate
{
int LOUD = 0;
int SOFT = 1;
int OFF = 2;
void talk();
void listen();
}
class Telephone implements Communicate
{
public void talk() { … } //implementation of interface
public void listen() { … } // other methods implemented
public void call ( String number) { … } //method member
implemented
}
class Professor implements Communicate
{
public void talk() { … } //implementation of interface
public void listen() { … } // other methods implemented
void Lecture( String topic) { … }
}
6
Programming With Java
ICS201
Example (Interface)
o The keyword implements indicates that the class
implements one or more interfaces.
o Using Objects with common interfaces methods
Professor prof = new Professor( “XXXXXX" );
Telephone tel = new Telephone( “111" );
prof.listen();
tel.listen();
7
Programming With Java
ICS201
Exercise (Interface)
// What compile-time error generated for
this program?
interface B
{
void display();
}
class D0
{
}
class D1 implements B
{
public void display()
{
System.out.println( "D1" );
}
}
class D2 implements B
{
public void display()
{
System.out.println( "D2" );
}
}
class InterfaceRefVariable
{
public static void main( String
[] args)
{
B b = new D0();
b.display();
b = new D1();
b.display();
b = new D2();
b.display();
}
}
8
Programming With Java
ICS201
Interface
o To implement an interface, a concrete class must do
two things:
1. It
must
include
the
phrase
implements
Interface_Name at the start of the class definition.
 If more than one interface is implemented, each
is listed, separated by commas.
2. The class must implement all the method headings
listed in the definition(s) of the interface(s).
9
Programming With Java
ICS201
Example (Interface Reference)
// Interface extends one or more
interfaces
interface J {
int i=200;
int J1();
}
interface K {
double K1();
}
interface L extends J, K
{
boolean L1();
}
class I implements L {
public int J1()
{
return 4;
}
public double K1()
{
return 7.98;
}
public boolean L1()
{
return true;
}
}
class InterfaceInheritance
{
public static void main( String[]
args)
{
I a = new I();
System.out.println(a.i);
System.out.println(a.J1());
System.out.println(a.K1());
System.out.println(a.L1());
}
}
10
Programming With Java
ICS201
Interface
o The keyword extends is used to define an inheritance
relationship between interfaces.
o An interface may directly extend multiple interfaces.
interface L1
{
void f();
The following program generates a
void g();
compile-time error.
}
 Interface L1 declares f() and g().
interface L2 extends L1
Interface L2 declares the same
{
except return type of g() is different.
void f();
int g();
The compiler identifies it as an error.
}
class CE
{
public static void main(String [] args)
{
System.out.println( "Hello" );
}
}
11
Programming With Java
ICS201
Exercise (Interface Inheritance)
Write
a
program
that
illustrates
interface
inheritance. Interface P is extended by P1 and
P2. Interface P12 inherits from both P1 and P2.
Each interface declares one constant and one
method. Class Q implements P12. Instantiate Q
and invoke each of its methods. Each method
displays one of the constants.
12
Programming With Java
ICS201
The instanceof Operator
o The instanceof operator is used to determine if an
object is of a particular class or implements a specific
interface.
o Syntax: varName instanceof type
o varName is an object reference variable
o type is the name of either a class or an interface
o The expression evaluates to true if varName is a type.
Otherwise, it evaluates to false.
13
Programming With Java
ICS201
Example (The instanceof Operator)
abstract class Fish
{
abstract void display();
}
abstract class SaltWtrFish extends Fish
{
}
abstract class FreshWtrFish extends Fish
{
}
class Trout extends FreshWtrFish
{
void display()
{
System.out.println( "Trout" );
}
}
class Tuna extends SaltWtrFish
{
void display()
{
System.out.println( "Tuna" );
}
}
class InstantofOperator
{
public static void main( String[] arg)
{
Fish f[] = new Fish[3];
f[0] = new Trout();
f[1] = new Tuna();
f[2] = new Trout();
for(int j = 0; j < 3; j++)
if ( f[j] instanceof FreshWtrFish )
f[j].display();
}
}
Output:
Trout
Trout
14
Programming With Java
ICS201
Example (The instanceof Operator)
interface Vehicle
{
void drive();
}
abstract class Mammal { }
class Bear extends Mammal { }
class Elephant extends Mammal implements Vehicle
{
public void drive()
{
System.out.println( "Elephant: Drive" );
}
}
class Horse extends Mammal implements Vehicle
{
public void drive()
{
System.out.println( "Horse:Drive" );
}
}
class Lion extends Mammal{ }
class InstantofInterface
{
public static void main( String[] ar)
{
Mammal m[] = new Mammal[4];
m[0]=new Elephant();
m[1]=new Bear();
m[2]=new Horse();
m[3]=new Lion();
for( int j = 0; j < 4; j++)
{
if ( m[j] instanceof Vehicle)
{
Vehicle v = (Vehicle)m[j];
v.drive();
}
}
}
Output:
}
Elephant: Drive
Horse: Drive
15
Programming With Java
ICS201
Exercise (The instanceof Operator)
Write a program that demonstrate the instanceof operator.
Declare interface I1 and I2. Interface I3 extends both of these
interface. Also declare interface I4. Class X implements I3.
Class W extends X and implements I4. Create an object of class
W. Use the instanceof operator to test if object implements each
of the interface and is of type X.
16
Programming With Java
ICS201
The comparable Interface
o Chapter 4 discussed the Merge Sort and the quick sort
algorithms, and examined a method for sorting an array into
increasing order
 This code could be modified to sort into decreasing order,
or to sort strings instead
 Each of these methods would be essentially the same, but
making each modification would be a nuisance.
o The only difference would be the types of values being sorted,
and the definition of the ordering.
o Using the Comparable interface could provide a single sorting
method that covers all these cases.
17
Programming With Java
ICS201
The comparable Interface
o The Comparable interface is in the java.lang package,
and so is automatically available to any program.
o It has only the following method heading that must be
implemented:
public int compareTo(Object other);
o It is the programmer's responsibility to follow the
semantics
of
the
Comparable
interface
when
implementing it.
18
Programming With Java
ICS201
The comparable Interface
o The method compareTo must return:
 A negative number if the calling object "comes
before" the parameter other.
 A zero if the calling object "equals" the parameter
other.
 A positive number if the calling object "comes after"
the parameter other.
o If the parameter other is not of the same type as the
class being defined, then a ClassCastException should be
thrown.
19
Programming With Java
ICS201
Simple Use of Inner Classes
o Inner classes are classes defined within other classes.
o The class that includes the inner class is called the outer
class.
o There is no particular location where the definition of the
inner class (or classes) must be place within the outer
class.
o Placing it first or last, however, will guarantee that it is
easy to find.
20
Programming With Java
ICS201
Simple Use of Inner Classes
o An inner class definition is a member of the outer class in
the same way that the instance variables and methods of
the outer class are members.
o An inner class is local to the outer class definition.
o The name of an inner class may be reused for something
else outside the outer class definition.
o If the inner class is private, then the inner class cannot
be accessed by name outside the definition of the outer
class.
21
Programming With Java
ICS201
Simple Use of Inner Classes
o There are two main advantages to inner classes.
 They can make the outer class more self-contained
since they are defined inside a class.
 Both of their methods have access to each other's
private methods and instance variables.
o Using an inner class as a helping class is one of the most
useful applications of inner classes.
 If used as a helping class, an inner class should be
marked private.
22
Programming With Java
ICS201
Simple Use of Inner Classes
o Within the definition of a method of an inner class:
 It is legal to reference a private instance variable of the
outer class
 It is legal to invoke a private method of the outer class
o Within the definition of a method of the outer class
 It is legal to reference a private instance variable of the
inner class on an object of the inner class
 It is legal to invoke a (nonstatic) method of the inner class
as long as an object of the inner class is used as a calling
object
o Within the definition of the inner or outer classes, the modifiers
public and private are equivalent.
23
Example(Use of Inner Classes)
Programming With Java
ICS201
public class University{
private class Student {
private String ID ;
private int Age ;
private String Grade ;
private Student S ;
public String getInfo( ) {
return S.Grade + “ “ + S.getStudentInfo() ;
}
} // end of outerclass
public Student (string I, int A, String G) ………
{
this.ID = I ;
this.Age = A ;
this.Grade = G ;
}
public String getGrade( ) {
return Grade ;
}
public String getStudentInfo( ) {
return ID +” ” +Age;
}
} // end of inner class
24