Transcript interface
Enhanced Class Design -- Introduction
We now examine several features of class design and
organization that can improve reusability and system
elegance
We will focus on:
abstract classes
formal Java interfaces
packages
1
Nested Classes
In addition to a class containing data and methods, it can also contain
other classes
A class declared within another class is called a nested class
Outer Class
Nested
Class
2
Nested Classes
A nested class has access to the variables and methods of
the outer class, even if they are declared private
In certain situations this makes the implementation of the
classes easier because they can easily share information
Furthermore, the nested class can be protected by the outer
class from external use
This is a special relationship and should be used with care
3
Nested Classes
A nested class produces a separate bytecode file
If a nested class called Inside is declared in an outer class
called Outside, two bytecode files will be produced:
Outside.class
Outside$Inside.class
Nested classes can be declared as static, in which case
they cannot refer to instance variables or methods
A non-static nested class is called an inner class
4
Abstract Classes
An abstract class is used in a class hierarchy to organize common
features at appropriate levels
An abstract method has no implementation, just a name and signature
An abstract class contains abstract methods
Any class that contains an abstract method is by definition abstract
An abstract class cannot be instantiated
5
Abstract Classes – Some rules
The modifier abstract is used to define abstract classes
and methods
The child classes of the abstract class are expected to define
implementations for the abstract methods in ways
appropriate for them
If a child class does not define all abstract methods of the
parent, then the child is also abstract
An abstract class is often too generic to be of use by itself
6
Abstract Classes
See Dinner.java
Food
Beans
Franks
Pepperoni
7
Abstract Classes
// Class Food is an abstract representation of a food
item.
abstract class Food
{
// Returns calories of fat for the food item.
public abstract double CaloriesOfFat();
} // class Food
8
Class Pepporoni
// Class Pepperoni is derived from an abstract class
// and implements its method.
class Pepperoni extends Food
{
private double CaloriesOfFat = 100;
// Returns the number of fat calories.
public double CaloriesOfFat()
{
return CaloriesOfFat;
} // method
} // class Pepperoni
9
Dinner class
public class Dinner
{
// Creates a Pepperoni object and invokes its method.
public static void main (String[] args)
{
Pepperoni slice = new Pepperoni();
System.out.println (slice.CaloriesOfFat());
} // method main
} // class Dinner
10
Abstract Classes
See Printer.java
File
int NumberOfCharacters
Binary_File
Text_File
Image_File
11
Abstract Classes
An abstract method cannot be declared as final, because
it must be overridden in a child class
An abstract method cannot be declared as static,
because it cannot be invoked without an implementation
Abstract classes are placeholders that help organize
information and provide a base for polymorphic references
Abstract classes can contain methods with full definitions.
12
Interfaces
Till now we have used the term interface to mean the set of
service methods provided by an object.
That is, the set of methods that can be invoked through an
object define the way the rest of the system interacts, or
interfaces, with that object.
The Java language has an interface construct that formalizes
this concept
A Java interface is a collection of constants and abstract
methods
13
Basics of Interfaces
Consists of :
methods that are public and abstract
fields that are public, static, and final
Implemented by a class that declares it implements the interface and
the class defines implementations for all the interface methods
A class can implement multiple interfaces
14
Interfaces
A class that implements an interface must provide
implementations for all of the methods defined in the
interface.
This relationship is specified in the header of the class:
class class-name implements interface-name
{
}
See Soap_Box.java
15
Interfaces
A Java interface is a collection of abstract methods and
constants
An interface is used to formally define a set of methods that
a class will implement
16
Interfaces
interface is a reserved word
public interface Doable
None of the methods in an
interface are given
a definition (body)
{
public abstract void doThis();
public abstract int doThat();
public abstract void doThis2 (float value, char ch);
public abstract boolean doTheOther (int num);
}
A semicolon immediately
follows each method header
17
Interfaces
public class CanDo implements Doable
{
public void doThis ()
{
implements is a
// whatever
reserved word
}
public void doThat ()
{
// whatever
}
Each method listed
in Doable is
given a definition
// etc.
}
18
Interfaces
An interface cannot be instantiated
Methods in an interface have public visibility by default
A class formally implements an interface by
stating so in the class header
providing implementations for each abstract method in the
interface
If a class asserts that it implements an interface, it must define all
methods in the interface or the compiler will produce errors.
19
Interfaces
A class that implements an interface can implement other
methods as well
See Speaker.java Philosopher.java
See Dog.java
A class can implement multiple interfaces The interfaces
are listed in the implements clause, separated by commas
The class must implement all methods in all interfaces
listed in the header
20
Interface Philosopher
//Interface Philosopher lists the methods that must be
//defined by any class that implements the interface.
interface Philosopher
{
//============================
// Should be defined to return a statement made by
// particular philosopher
//============================
public abstract String pontificate();
} // interface Philosopher
21
// Class Kant represents the teachings of philosopher
//Immanual Kant. It implements the Philosopher interface,
//and therefore must define method pontificate.
class Kant implements Philosopher
{
//============================
// Returns a key philosophical statement by Kant.
//============================
public String pontificate()
{
return "Follow the Categorical Imperative!";
} // method pontificate
} // class Kant
22
Class Soap_Box
// driver class
public class Soap_Box
{
/============================
//Creates a Kant object and calls pontificate method .
//============================
public static void main (String[] args)
{
Kant immanual = new Kant();
System.out.println (immanual.pontificate());
} // method main
} // class Soap_Box
23
Polymorphism via Interfaces
An interface name can be used as the type of an object
reference variable
Doable obj;
obj = new Cando()
The obj reference can point to any object of any class that
implements the Doable interface
The version of doThis that the following line invokes
depends on the type of object that obj is referring to:
obj.doThis();
24
Polymorphism via Interfaces
That reference is polymorphic, which can be defined as
"having many forms"
That line of code might execute different methods at
different times if the object that obj points to changes. See
Talking.java
Polymorphic references are often resolved at run time; this
is called dynamic binding though there is a way to have it
done at compile time we will look at later
25
Interfaces
//***********************************************
Demonstrates the declaration of an interface.
Dog and Philosopher will implement it and provide
implementations for the speak and announce methods
***********************************************/
interface Speaker
{
public abstract void speak ();
public abstract void announce (String str);
}
26
//********************************************************
// Dog provides implementation for the methods in the Speaker interface
//********************************************************
class Dog implements Speaker
{
//----------------------------------------------------------------// Prints this dog's philosophy.
//----------------------------------------------------------------public void speak ()
{
System.out.println ("woof");
}
//----------------------------------------------------------------// Prints this dog's philosophy and the specified announcement.
//----------------------------------------------------------------public void announce (String announcement)
{
System.out.println ("woof: " + announcement);
}
}
27
//********************************************************
// Philosopher provides implementation for the methods in
the Speaker interface and another method of its own
//********************************************************
class Philosopher implements Speaker
{
private String philosophy;
//----------------------------------------------------------------// Establishes this philosopher's philosophy.
//----------------------------------------------------------------public Philosopher (String philosophy)
{
this.philosophy = philosophy;
}
//----------------------------------------------------------------// Prints this philosophers's philosophy.
//----------------------------------------------------------------public void speak ()
{
System.out.println (philosophy);
}
28
//----------------------------------------------------------------// Prints the specified announcement.
//----------------------------------------------------------------public void announce (String announcement)
{
System.out.println (announcement);
}
//----------------------------------------------------------------// Prints this philosophers's philosophy multiple times.
//----------------------------------------------------------------public void pontificate ()
{
for (int count=1; count <= 5; count++)
System.out.println (philosophy);
}
}
29
class Talking
{
//----------------------------------------------------------------// Instantiates two objects using an interface reference and
// invokes one of the common methods. Then casts the interface
// reference into a class reference to invoke its unique method.
//----------------------------------------------------------------public static void main (String[] args)
{
Speaker current; // Speaker is an Interface
current = new Dog(); // class dog implements the interface
current.speak(); // current is now a dog
current = new Philosopher ("I think, therefore I am.");
current.speak(); // current is now a philosopher
((Philosopher) current).pontificate();
}
}
30
Interfaces
An interface name can be used as a generic reference type
name
A reference to any object of any class that implements that
interface is compatible with that type
For example, if Philosopher is the name of an
interface, it can be used as the type of a parameter to a
method
An object of any class that implements Philosopher can
be passed to that method
31
interfaces
E.g:
public void Ideas(Philosopher p)
{
// some code
}
Any class implementing the Philosopher interface can
be sent as a parameter to this method.
32
Interfaces & Constants
Unlike interface methods, interface constants require
nothing special of the implementing class
Constants in an interface can be used in the implementing
class as if they were declared locally
This feature provides a convenient technique for
distributing common constant values among multiple
classes
33
Interfaces
An interface can be derived from another interface, using the extends
reserved word
The child interface inherits the constants and abstract methods of the
parent
A class that implements the child interface must define all methods
in both the parent and child
Note that the interface hierarchy and the class hierarchy are distinct.
The interface hierarchy does not define an ISA relationship. A Dog is
not a Speaker. It’s ability to speak is a functionality it is given.
34
Interfaces - SUMMARY
An interface can be implemented by multiple classes
Each implementing class can provide their own unique
version of the method definitions
An interface is not a class, and cannot be used to instantiate
an object
An interface is not part of the class hierarchy
A class can be derived from a base class and implement
one or more interfaces
35
Interfaces
A class that implements multiple interfaces specifies all of
them in its header, separated by commas
The ability to implement multiple interfaces provides many
of the features of multiple inheritance, the ability to derive
one class from two or more parents
Java does not support multiple inheritance
36
Interfaces VS Abstract Classes
Note the similarities between interfaces and abstract
classes
Both define abstract methods that are given definitions by a
particular class
Both can be used as generic type names for references
However, a class can implement multiple interfaces, but can
only be derived from one class.
37
Interfaces - Details
Let B & C be classes. Assume that we make A the parent
class of B and C so A can hold the methods and fields that
are common between B and C.
Sometimes a method in B is so different from the same
method in C there is no shared implementation possible in
A. We can make A an abstract class.
The methods in A then determine which methods must be
implemented in B and C.
38
Interfaces - Details
A can act as the super type, listing the methods that should
be implemented in B & C.
If all the methods in B must be implemented differently
from the same methods in C, make A an interface.
Interfaces can specify public methods but can not
implement them. Thus, one can not create an object from an
interface.
Interfaces can have fields. All fields in an interface are final
and static even if they are not explicitly declared as such.
39
Interfaces - Details
Interfaces have the same access levels as classes, public
and package.
A class can implement more one interface.
If a parent class implements an interface, its child classes
automatically implements the interface.
An interface, like a class, defines a type.
Fields, variables, and parameters can be declared to be of a
type defined by an interface.,
40
Interfaces – Static Fields
1. Constants – also called fields - an be declared in an
interface.
2. All constants are public static and final.
3. Declaring a constant to be any other access level except
public is a compile error.
4. If no access level is given, it defaults to public.
5. If a constant is not explicitly declared to be static or final,
the field is still static and final.
41
Interfaces - Example
interface WithStatic
{
public static final int EXPLICIT = 42;
public static int IS_FINAL =
12;
public int IS_FINAL_AND_STATIC = 3;
protected int COMPILE_ERROR = 4;
public int NO_VALUE_COMPILE_ERROR;
}
42
STATIC FIELDS - EXAMPLE
class Radio implements WithStatic
{
public void AM()
{ System.out.println( IS_FINAL );
} // close class
}
class Test
{
public static void main( String args[] )
{
System.out.println( WithStatic.EXPLICIT );
System.out.println( Radio.EXPLICIT );
Radio megaBass = new Radio();
System.out.println( megaBass.EXPLICIT );
megaBass.AM(); }
}
43
Extending Interfaces One interface can inherit from
another interface, supporting multiple inheritance.
interface Door
{
public void open();
public void close();
}
interface LockableDoor extends Door
{
public void lock();
public void unlock();
}
44
Extending Interfaces
class CarDoor implements LockableDoor
{
private boolean isLocked = false;
public void open()
{
if ( !isLocked)
System.out.println( "Enter the car" );
}
public void close()
{
System.out.println( "Closing the door");
}
45
Extending Interfaces
public void lock()
{ isLocked = true; }
public void unlock() { isLocked = false; }
} //close class
public class TestDoor
{
public static void main( String[] args )
{
Door d = new CarDoor();
d.open();
d.lock(); //Compile error
LockableDoor better = (LockableDoor) d;
better.lock();
//OK
}
}
46
Method Name Conflicts
A class implements two interfaces that each have a method with
the same name,
Square():
If both Square() methods have different signatures, then the
class implements two overloaded methods.
If both methods have the same signature and the same
return type, then the class implements only the one square()
method.
47
Method Name Conflicts
If both Square() methods have the same signature and
different return types, then the class can not implement both
interfaces.
If both methods have the same signature, same return
type but differ in the types of exceptions they throw, then
the class implements only the one method, but it must
contain the exceptions of both methods.
If a class implements two interfaces that each have a field
with the same name, say bar, then the class must use the
full names for the fields.
48
Interfaces
The Java standard class library contains many interfaces
that are helpful in certain situations.
The Comparable interface contains an abstract method
called compareTo, which is used to compare to objects.
The String class implements Comparable which gives
us the ability to put strings in alphabetical order
49
Comparable
It is advisable to override the compareTo method in your
classes if you wish to compare two objects according to
some specifaction. E.g. comparing SSN’s in the student
class.
50
Packages
A Java package is a collection of classes
The classes in a package may or may not be related by
inheritance
A package is used to group similar and interdependent
classes together
The Java API is composed of multiple packages
The import statement is used to assert that a particular
program will use classes from a particular package
51
Packages
A programmer can define a package and add classes to it
The package statement is used to specify that all classes
defined in a file belong to a particular package
The syntax of the package statement is:
package package-name;
package Graph;
e.g.
It must be located at the top of a file, and there can be only
one package statement per file
52
Packages
The classes must be organized in the directory structure
such that they can be found when referenced by an import
statement
The import statement specifies particular classes, or an
entire package of classes, that can be used in that program
53
Packages
As a rule of thumb, if you will use only one class from a
package, import that class specifically
import Java.util.Iterator // imports a single class in the util package
If two or more classes will be used, use the * wildcard
character in the import statement to provide access to all
classes in the package
import java.util.*; // imports all the classes in the package
54