Next: Lecture 9 Up: Home
Readings
-
On the course Web page look at:
-
In the text read
-
Chapters 10
-
Exercises: redo 6.22-6.24 using inheritance.
Drawing shapes by using upper the left corner reference. example circle.
setSize(width, height);
page.drawRect(x, y, width, height);
page.drawLine(x, y, x_end, y_end);
Storm works by repainting the applet each time. Bouncing_Ball and Rotating_Disk
example uses setXORMode.
//*******************************************************************
//
// Rotating_Disk.java In Text Applet
//
// Authors: Lewis and Loftus
//
// Classes: Rotating_Disk
//
//*******************************************************************
import java.applet.Applet;
import java.awt.*;
public class Rotating_Disk extends Applet {
//===========================================================
// Uses ovals to simulate a rotating disk.
//===========================================================
public void paint (Graphics page) {
int width = 0, height = 40;
int x = 100, y = 100, warp = 1;
page.setXORMode (getBackground());
for (int change=1; change < 200; change++) {
width += warp * 2;
x -= warp;
if (width == 0 || width == 40)
warp *= -1; //switch between growing and shrinking
page.fillOval (x, y, width, height);
for (int pause=1; pause <= 100000; pause++);
page.fillOval (x, y, width, height); // erase oval
}
} // method paint
} // class Rotating_Disk
Inheritance
Motivation for inheritance
-
easier to derive new classes
(abstraction chapter 4 page 145)
-
allows software to be reused
-
add and modify (overriding) methods and
variables in child classes
-
well designed class hierarchies add a new
dimension to well designed programs
-
allows polymorphism - allowing object references of a class
to point to objects of children of that class.
Inheritance
-
derive a new class from an existing class with
similar characteristics
-
new derived class - extended
-
all methods are defined
for the derived class
-
all public methods are accessible
as if declared locally.
-
An inheriting child class ``is a'' parent with some variations in fields
and/or methods.
-
the child is more specific than the parent class
-
(child) Dictionary (inherits) extends
(parent) Book
Super, Defined and Inherited
-
Words2 Example
-
Exceptions to inheritance accessibility
(maintaining encapsulation)
-
constructor - use of super(...);
to invoke parent's constructor
-
private methods not directly accessible
-
protected methods & fields are inherited,
-
compromise to the extremes of public and
private
-
protect's scope is the parent's package.
-
See Appendix F
Overriding inherited methods
-
redefine method with same signature
-
the object's method is invoked
i.e. the class on the right hand side
Class hierarchies
-
many generations
-
results in a generalized tree structure
-
common features should be located near top to minimize duplication
of effort.
(maximizing reuse)
-
revising and extending hierarchies is less likely to introduce errors
in
existing code than modifying code.
Hierarchies organization - chosen with an eye to dynamic use
in programs
-
form is determined by the algorithm's you write
and ways you want to manipulate objects
Object class
-
all classes inherit the Object class
-
most classes override Objects methods
-
toString() - returns String represents
object
-
equals (Object obj) - returns boolean true if aliases are equal
-
hashCode() - returns unique number for an object
Polymorphism - references and class hierarchies
-
allows references of a class to point to objects of children of that class.
-
instanceof operator
-
objectName instanceof ClassName
-
Variety example uses Vector class
-
Object something;
Vector collector = new Vector();
//...
int temp;
Object something;
for (int count=0; count < 4; count++) {
something = collector.elementAt (count);
if (something instanceof Integer) {
temp = ((Integer)something).intValue()+20;
...}...}
Programs
-
Words.java
-
Creating subclasses
-
Words2.java
-
The Super Reference
-
Eating.java
-
Defined versus Inherited
-
School.java
-
Student Example
-
Messages.java
-
Overriding methods
-
Firm.java
-
Employee Example (*)
-
Accounts.java
-
Savings Accounts Example (*)
-
Accounts2.java
-
3 Accounts Example (*)
-
Messages2.java
-
Polymorphism
-
Variety.java
-
Polymorphism instanceof operator (*)
-
Firm2.java
-
Paying Employee Example (*)
Enhanced Class Design
-
abstract classes and their subclasses
-
interfaces (abstract)
-
polymorphic support to abstract classes and interfaces
-
grouping interdependent classes into
a package
Abstract classes and inheritance
-
identified with modifier abstract
-
A generic concept or blueprint
-
methods not implemented i.e. can't be instantiated
-
e.g. food pizza, beans, veggie dogs
-
can have both abstract & nonabstract
methods
-
can be inherited by a nonabstract class
-
can be inherited by another
abstract class
Abstract methods
-
have no body of statements
-
must be inherited and overriden to be of use
-
abstract public return-type method (parameters);
abstract can't be used with final or static
inheritance of an abstract class by a nonabstract class
-
methods must be overriden
inheritance of an abstract class by another
abstract class
-
does not have to implement its
abstract methods
Interfaces - Encapsulation
-
contants hide magic numbers
-
group common methods together
-
applications may require more than one class hierarchy or parent-child
inheritance tree
-
interfaces allow two or more class hierarchies to be linked in the
same application
interface interfaceName {
constant-declarations-implicitly-public-final
all-methods-implicitly-public-abstract
}
Interfaces
classes that implement an interface
-
use constants as if declared locally
-
are forced to override all methods
-
can be used as a data type in formal parameters
-
matches any class or subclass than implements the interface
-
see Print_Logger.log in the Printer2 program.
-
public void log (Printable file) ...
class name implements interface1, interface2 {
overrides-all-methods-in-interface
}
an interface can extend another interface
interface extendedName extends interfaceName {
...
}
Encapsulation
Interfaces and abstract classes encapsulate information
Hiding information because
-
size of program contains too much for one person to grasp
-
multiple programmers work on different parts of the same program
Packages - further encapsulation
-
import package-name;
-
group interdependent classes &
interfaces
-
classes & interfaces in one file are
considered to be in one package
-
referenced by subdirectory name
containing class files
-
importing two packages that contain
the same class name need to be
disambiguated with the package-name i.e.
package_name.class_name.class_member
import java.io.*;
class Histogram { // ch6p23
int size;
int[] bins;
Histogram () {
size = 51;
bins = new int[size];
for (int i=0;i < size;i++) bins[i] = 0;
}
void add (int number) {
if (-1 < number && number < size) bins[number]++;
}
void print () {
System.out.println( "bin\tcount");
for (int i=0;i < size;i++)
if (bins[i] != 0)
System.out.println (" " + i + "\t" + bins[i]);
}
}
import java.io.*;
class HistogramCh6p24 extends Histogram { // ch6p24
int hi, low;
//int size; inherited from Histogram class
//int[] bins;
HistogramCh6p24 (int low, int hi) {
this.low = low;
this.hi = hi;
size = hi - low + 1;
bins = new int[size];
for (int i=0;i < size;i++) bins[i] = 0;
}
void add (int number) {
if (low <= number && number <= hi) bins[number-low]++;}
void print () {
System.out.println( "bin\tcount");
for ... if ...
System.out.println (" " + (i+low) + "\t" + bins[i]);
}}
Programs
-
Dinner.java
-
abstract inheritance
-
Printer.java
-
file structure
-
Soap_Box.java
-
interface - method
-
Protections.java
-
interfaces - constant
-
Printer2.java
-
interfaces and formal parameters
-
Readable_Files.java
-
implements multiple interfaces (*)
-
Simple_IO
-
packages Reader and Writer
-
Simple_IO_Test.java
-
imports packages from another file
-
Simple_IO_Test2.java
-
classes in one file
-
Simple_IO_Test3.java
-
disambiguate pkg.clss.mthd();
Next: Lecture 9 Up: Home
Craig MacDonald
Wed Jul 8 15:01:44 EDT 1998