Week 5: Inheritance and Interfaces
Quick Review
- Has-a relationship
- Is-a relationship
- Use relationship
For example, using methods from other classes in the same
package
Class relationships
- Containment (aggregation)
- one class is data in another
- class A "has-a" class B
- examples:
- Account contains Transaction
- Database contains Table
- Manager contains Employee
Inheritance
- a class can extend another to add or change data or
methods
- You can reuse or change the methods of existing classes,
as well as add new instance fields and new methods in
order to adapt them to new situations
- terminology
- superclass vs. subclass
- base class vs. derived class
- parent class vs. child class
- more general vs. more specific
- subclass inherits all of the superclass's
data and behavior
(subclasses have more functionality than
their superclasses)
- subclass "is-a",
"is-a-kind-of" superclass
- inheritance relation forms a hierarchy
- no multiple inheritance
- default is to extend Object
- examples:
- CheckingAccount extends Account
- SortedTable extends Table
- Manager extends Employee
- you can extend classes in the JDK
Examples:
// Superclass:
class Account
{
private String name;
private double balance;
public String getName ()
{
return name;
}
public double getAvailable ()
{
// Minimum balance is 50.
return balance - 50;
}
}
// Subclass:
class CheckingAccount extends Account
{
// Inherits all data and methods from Account.
private int lastCheckNumber;
public void writeCheck (double amount)
{
balance -= amount;
++lastCheckNumber;
}
// Override the superclass.
public double getAvailable ()
{
// Minimum balance is 5.
return balance - 5;
}
}
More on inheritance
- subclass constructors can call superclass's constructor
using super()
- must be in first line of constructor
implementation
- if not explicitly called, superclass's default
constructor will be called
- super can be viewed as a short hand for
"call the constructor of the parent class
with whatever parameters
- an overriding method may call its superclass's method of
the same name using super.methodName()
- When constructing a subclass, you need to indicate only
the differences between the subclass and superclass
- The ability to reuse superclass's method is automatic
Examples:
class Account
{
private String name;
private double balance;
// Constructor:
public Account (String customerName)
{
name = customerName;
balance = 0;
}
public double getInterestRate ()
{
// Most accounts get 5%.
return 0.05;
}
}
class CheckingAccount extends Account
{
private int lastCheckNumber;
// Constructor:
public CheckingAccount (String customerName,
int initialCheckNumber)
{
// Call superclass's constructor.
super (customerName);
lastCheckNumber = initialCheckNumber;
}
public double getInterestRate ()
{
// Checking accounts get half the normal rate.
// Call superclass's method to get the normal rate.
double normalRate = super.getInterestRate ();
return normalRate / 2;
}
}
Inheritance Hierarchy
We can have the following parent/child class relationship
Employee <-- Manager <-- Executive
Account <-- CheckingAccount <-- NOWAccount
Hint: Only use inheritance when any object of the subclass
must be useable in place of the superclass object
Can We Do This
// We have Employee <- Manager
Employee[] staff = new Employee[3];
Manager boss = new Manager("Richard Sinn", 100000, myDay);
staff[0] = boss; // Can we do this
...
boss = staff[i] // Is this right, which class will get more fields
Polymorhism
- The ability of an object to decide what method to apply
to itself, depending on where it is in the inheritance
hierarchy, is usually called polymorphism (message is the
same, respond will be different)
- Application spell out the general way, individual classes
in the hierarchy are responsible for carrying out the
details
- code can be generically written in terms of superclass
but still work with subclasses
- variables declared of superclass type can reference
subclass objects
- not vice versa!
- helps avoid big switch or if-then-else constructs
- Prevent inheritance by using final
final class Manager
(Efficiency - can be put inline; Safety - application
control)
Examples:
// Initialize an array of accounts. Some may actually be subclasses
// of account.
Account[] accountList = new Account[3];
accountList[0] = new Account ("Bob");
accountList[1] = new CheckingAccount ("John");
accountList[2] = new Account ("Betty");
// Iterate through the list generically.
double totalInterestRate = 0;
for (int i = 0; i < accountlist.length; ++i)
totalInterestRate += accountList[i].getInterestRate ();
double averageinterestrate=totalInterestRate / accountlist.length;
Casting
staff is an Employee array
staff[0] = new Manager("Richard Sinn");
staff[1] = new Employee("Joe IBMer");
Manager boss = (Manager) staff[0]; // Corrent ?
Manager boss = (Manager) staff[1]; // Error ?
// Can use the following code to check:
if (staff[i] instanceof Manager)
{
boss = (Manager) staff[1];
...
}
Casting can only be used in inheritance hierarchy
Use instanceof to check a hierarchy before casting from a
parent to a child class
This is kind of complex ... why use it ...
Abstract classes
- An abstract class has at least one
abstract method
- define a method without an implementation
- cannot be instantiated
- must be subclassed
- enforced by compiler
- useful for code reuse
- useful for defining commonality among several potential
subclasses
Examples:
abstract class Account
{
// ... other definitions
// Subclasses must define the format of the monthly
// statement. No implementation is provided.
public abstract void printMonthlyStatement ();
}
class CheckingAccount extends Account
{
// ... other definitions
// Here we provide an implementation.
public void printMonthlyStatement ()
{
// ... implementation
}
}
Protected access
- data and methods can be declared to be protected
- accessible within class and any subclass
- not accessible to other classes
java.lang.Object - Cosmic Superclass
- the parent of all classes
- getClass() // Information about class
- equals() // point to same area of memory
- toString() // string value of the object
- many others
- Now ... we know how to start reading the JDK
documentation
Java Control Visibility - Quick Review
- Visible to the class only (private)
- Visible to the world (public)
- Visible to the package and all subclasses (protected)
- Visible to the package (the default - no modifier needed)
Interfaces
- Java way of dealing with common situation of wanting a
class to reflect the behavior of tow (or even more)
parents - multiple inheritance
- This exits because of subclass can only extends from one parent
class
- (Compiler less complex)
- Interface is a promise of your class that will implement
certain methods with certain signatures
- nothing to do with graphical user interfaces (GUI)
- like a completely abstract class
- defines an interface, but no implementation and no data
- a class may implement an interface - it implements all of
the methods
- useful when needing to code to a generic interface
- implementation might not be important at this
time
- allows multiple implementations to be provided
later
- examples:
- Queue (possible implementations: ArrayQueue,
VectorQueue)
- InputSteam (implementations: FileInputStream,
BufferedInputStream, SocketInputStream)
- JDBC (Java Database Connectivity - java.sql
package in JDK)
- collection of interfaces that define
generic access to a database
- database companies provide
implementations for specific products
- applications can write to JDBC interfaces
and customers can plug in specific
implementations as needed
Examples:
interface NumberGenerator
{
public int nextNumber ();
public int prevNumber ();
}
class OddNumberGenerator
implements NumberGenerator
{
int currentNumber = -1;
public int nextNumber ()
{
currentNumber += 2;
return currentNumber;
}
public int prevNumber ()
{
currentNumber -= 2;
return currentNumber;
}
}
class RandomNumberGenerator
implements NumberGenerator
{
public int nextNumber ()
{
// ... generate new random number
}
public int prevNumber ()
{
// ... return previous random number
}
}
More on interfaces
- all methods are public
- polymorhpism works the same as with inheritance
- a class may implement multiple interfaces
- an interface may extend another interface
- used extensively in graphical user interface programming
- name classes, data, and methods appropriately
- class names - start with uppercase letter, use a
noun
- data names - start with lowercase letter, use a
noun
- method names - start with lowercase letter, use a
verb
- class with superclass can implement interface as well
For example:
class Tile extends Rectangle implements Sortable
Lab
Part I
- Create a subclass of Hashtable called MyHashtable that overrides
the put() method that enforces a limit to how many
elements the Hashtable may contain. Add a constructor
takes a parameter to specify this maximum and a
getMaximum() method that returns the maximum.
- Create a class called Week5 that
contains the main() method for an application. This
main() method should create a MyHashtable, add several
items (a few more than the maximum). It should then print
out the some of the entries to verify that it only
contains the maximum number of elements.
Part II
- Create a interface called Shape
that defines the following methods:
- double getArea() - to return the area of a shape
- double getPerimeter() - to return the perimeter
of the shape
- Create two implementations of the Shape interface called Rectangle and Circle.
- In Week5:
- Create an array of assorted Shapes.
- Iterate through the array and print out the areas
and perimeters of each.
Copyright
1996-2001 OpenLoop Computing. All rights reserved.