Title: Enhanced%20Class%20Design%20--%20Introduction
1Enhanced 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 polymorphism
- Extending Interfaces
2Nested 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
3Nested Classes
- A nested class has access to the
- variables and methods of the outer class,
- even if they are declared private
- This makes the implementation of the classes
easier -
- because they can easily share information
4Protecting the inner class
-
- The nested class can be protected by
- the outer class from external classes
- This is a special relationship
5Nested 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
- OutsideInside.class
6Inner classes
- Nested classes can be declared as static.
- in that case, they cannot refer to instance
variables or methods declared in the class - A non-static nested class is called an inner
class
7Abstract 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
-
8Class 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
-
9Dinner 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
-
10Abstract Classes
11Interfaces
- A Java interface is a collection of constants and
abstract methods - Lets review an example
12Interfaces
interface is a reserved
word
public interface Doable public abstract void
doThis() public abstract int doThat()
public abstract void doThis2 (float value, char
ch) public boolean doTheOther (int num)
A semicolon immediately follows each method header
13 Interfaces
public class CanDo implements Doable public
void doThis () // whatever
public void doThat () // whatever
// etc.
14 interface, Geometry
- The interface, Geometry, consists of
- one static constant and two abstract methods.
- public interface Geometry
-
- public static final double PI 3.14159 // a
constant - public abstract double area()
- public abstract double perimeter()
-
15Interfaces
- Unlike a class
- all methods of an interface are abstract, i.e.,
- there are no implementations at all, and
- an interface has no instance variables.
- Like an abstract class,
- an interface cannot be instantiated.
16- In contrast to an abstract class,
- a class does not extend an interface.
- Instead, a class
- implements an interface.
17- Problem Statement
- Define Circle, Square, and Triangle classes
- each of which implements the Geometry
interface. - Java Solution
- The following classes implement Geometry,
therefore, - each class is required to implement the area()
and perimeter() methods.
18Circle
- public class Circle implements Geometry
-
- private double radius
-
- public Circle() // constructdor
-
- radius 0.0
-
- public Circle (double r) // constructdor
-
- radius r
-
- public double perimeter() // method
-
- return 2PIradius
-
- public double area() // method
19Class Square
- public class Square implements Geometry
- private double side
-
- public Square() // CONSTRUCTORS
-
- side 0.0
-
- public Square (double s)
-
- side s
-
- public double perimeter() // METHODS
-
- return 4side
-
- public double area()
-
- return sideside
-
20 CLASS Triangle
- public class Triangle implements Geometry
-
- // three sides a,b,c
- private double a,b,c
- public Triangle (double a1,
- double b1, double c1)
-
- a a1
- b b1
- c c1
-
- public double perimeter()
-
- return abc
-
- public double area()
-
- double s (abc)/2.0
- return
- Math.sqrt(s(s-a)(s-b)(s-c))
-
-
21The Comparable Interface
- Java also provides a large number of ready-made
interfaces. - One of the most useful Java-supplied interfaces
- is the Comparable interface.
-
- Comparable is an interface with just one method,
- compareTo(...)
-
22 interface Comparable
- public interface Comparable
-
- public abstract int compareTo(Object o)
-
- compareTo(...) returns an integer and
- accepts any Object reference as an argument.
23The Comparable Interface
- A class that implements the Comparable interface
implements compareTo(...) so that - a.CompareTo(b) returns a negative integer, if a
is less than b, - a.CompareTo(b) returns 0, if a equals b, and
- a.CompareTo(b) returns a positive integer, if a
is greater than b. - A class that implements Comparable is
-
- lets its clients know that its objects can
be compared.
24The Comparable Interface
- Problem statement
- Define a Production hierarchy with Film and Play
as - child classes.
- Film and Play implement the Comparable interface.
25- A Film class has attributes ( instance
variables) - title,
- director,
- screenwriter, and
- total box office gross, in millions of dollars
adjusted for inflation. - The methods of a Film class include
- constructors,
- getters and setters, and
- a method that displays the values of each
attribute.
26- Like a Film class , a Play class has
- a title,
- a director, and
- a writer or playwright.
- Additionally, a Play object holds the number of
performances of a play. - The Play methods are
- getter and setter methods, and
- a method that displays the values of each
attribute.
27A Play class and a Film class - Implement
Comparable Interface and extend Productions
28Inheritance by Factoring
- The Play class and the Film class are very
similar - and share many of the same attributes and
methods. - They both will extend another class Production -
it will contain the methods and attributes common
to both. - This is called Inheritance by Factoring
29Inheritance Hierarchy
- Play extends Production Film extends Production
- They also both implement the Comparable
Interface
30- Because Play implements Comparable, Play must
implement compareTo(). - public class Play extends Production implements
Comparable - // OTHER METHODS
- public int compareTo(Object p) // from the
Comparable interface -
- if ( ! (p instanceof Play) ) // p must
BE A PLAY OBJECT -
- System.out.println("Error Object
does not belong to Play") - System.exit(0)
-
-
- // p must be cast to TYPE Play
- if (performances lt ((Play) p).performances)
return -1 - if (performances gt (( Play
)p).performances) - return 1
- return 0
-
31Examine the Code - the instanceOf operator
-
- // method defined in the Comparable interface
-
- public int compareTo(Object p)
- // p must BE A PLAY OBJECT
- if ( ! (p instanceof Play) )
- System.out.println("Error Object does
not belong to Play
class") - System.exit(0) // exits the program
-
32Examine Code Casting Objects
- // p must be cast to TYPE Play
- if (performances lt ((Play) p).performances)
- return -1 // number of
performances less than -
- if (performances gt (( Play
)p).performances) - return 1 // number of
performances greater than -
- // returns they are equal
- return 0
-
33Comparable interface
- The following compareTo() method is located in a
class of type FILM -
- The Film class implements Comparable and extends
the Production class
34- COMPARISON OF BOX OFFICE GROSSES FOR THE TWO FILM
OBJECTS, returning 0, 1 or -1 -
- public int compareTo(Object p)// p should be
a Film object -
- if ( !(p instanceof Film)) // p
must BE A FILM OBJECT - System.out.println("Error object
must belong to Film") - System.exit(0)
-
- // Now cast p to a FILM object and compare
values - if (boxOfficeGross lt ((Film) p
).boxOfficeGross ) return -1 -
- if (boxOfficeGross gt ((Film)p).boxOfficeGro
ss) return 1
35Interfaces Constants
- 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 eg. - The value of pi 3.14159265
36Interfaces
- An interface can extend other interfaces
- 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
37Class and Interfaces Hierarchy
- Note that the interface hierarchy and the class
hierarchy are distinct. - The interface hierarchy does not define an ISA
relationship. - Its ability to speak is a functionality it is
given.
38Interfaces - 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 of the Interface - An interface is not part of the class hierarchy
- A class can be derived from a base class and
implement one or more interfaces
39Interfaces
- 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
40- Some details on when to use and interface or an
abstract class - If Abstract class A requires abstract
methods - - should classes B and C extend it or
implement it ? - Rules
- If all the methods in B must be
- implemented differently from the same
methods in C, -
- make A an interface.
41INTERFACES
- The methods in A then require that these methods
must be implemented in B and C. - A can act as the super type, listing the methods
that MUST be implemented in B C.
42Interfaces - Review
- 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.
43Interfaces Static Fields
- Fields can be declared in an interface.
- All fields are public, static and final.
(Constants) - Declaring a field to be any other access level
except public is a compile error. - If no access level is given, it defaults to
public. - If a field is not explicitly declared to be
static or final, the field is still static and
final.
44Interfaces - Example
- interface WithStatic // CONTAINS STATIC
CONSTANTS -
- public static final int EXPLICIT 42
// VALID - public static int IS_FINAL 12 //
VALID - public int IS_FINAL_AND_STATIC 3 //
VALID - protected int COMPILE_ERROR 4
public int NO_VALUE_COMPILE_ERROR
45STATIC 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 ) //
uses interface name -
- System.out.println( Radio.EXPLICIT ) // uses
class name - Radio megaBass new Radio() // create
object of class - System.out.println( megaBass.EXPLICIT ) //
uses object name - megaBass.AM()
46Method Name Conflicts
- A class implements two interfaces that each have
a method with the same name, - Square()
- If both Square() methods in each interface have
different signatures( and type of parameters), - 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.
47Method Name Conflicts
- If both Square() methods have the same signature
and different return types, - then the class can not implement both interfaces.
48Conflicting interfaces
- If both methods have the
- 1. same signature,
- 2. 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.
49- If a class implements two interfaces that each
have a field with the same name, say bar, - then the class must use the full interface
names for the fields.
50- 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() -
51Extending Interfaces
- class CarDoor implements LockableDoor
- private boolean isLocked false
- // methods inherited from Interface DOOR
- public void open()
- if ( !isLocked)
System.out.println( "Enter the car" ) - public void close()
- System.out.println( "Closing
the door")
52Extending Interfaces
- // methods inherited from Lockable door
- public void lock()
- isLocked true
- public void unlock() isLocked false
- //close class
-
53Some issues with extending Interaces
- public class TestDoor
-
- public static void main( String args )
-
- Door d new CarDoor()
- d.open() // open() is in Door
Interface - //Compile error lock() not in Door Interface
- d.lock() // lock is in Lockable
interface - // must cast d to a lockable door
- LockableDoor better (LockableDoor)
d - better.lock() //OK
-
-
54Packages
- 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
55package
- 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
56Packages
- 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 e.g.
- package Graph
- It must be located at the top of a file, and
there can be only one package statement per file
57Packages
- 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
58Packages
- As a rule of thumb, if you will use only one
class from a package, import that class
specifically - imports a single class in the util package
- import Java.util.Iterator
- 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 -