 |
Defining classes - Part 2
|
Designing Classes
-
Designing and developing classes is difficult!
-
Can't do ad hoc
-
Need a more systematic approach. Why?
-
Don't waste time
-
Reduce errors
-
Allow others to re-use our code
-
So, here's one approach (learn additional, more rigorous techniques in
later courses)
-
Identify class(es)
-
Decide what behavior class will provide (informal)
-
Begin to specify prototypes, i.e., define its interface - interface to
a class consist of set of methods that can be invoked on instances of class.
-
Write a sample program that uses the class - sometimes called a driver
- helps us determine if design is sensible
-
Write skeleton class - class boilerplate, method prototypes, empty method
bodies
-
Implement methods and test using driver.
Identify Classes
For example, developing program for a real estate office. House
would probanly be appropriate class. (As might others of course.)
Identify Behavior
-
Specify the style
-
Specify the location
-
Specify the asking price
-
Return a description of the house
-
Return a code for the house based on a given prefix
-
Create a house
-
Create a house based on another house
-
...
Interface and Prototypes
-
class House
-
public void setStyle (String theStyle)
-
public void setLocation (String where)
-
public void setPrice (String currentPrice)
-
public String describe ()
-
public String code (String prefix)
-
public House () // no return type
-
public House (House similarHouse) // no return type
Driver
class TryHouse {
public static void main (String arg[]) {
House someHouse = new House ();
someHouse.setStyle ("Ranch");
someHouse.setLocation ("Briarwood");
someHouse.setPrice ("100000");
System.out.println (someHouse.describe());
anotherHouse = new House (someHouse);
}
}
The Class Skeleton
class House {
public House () {
//statements
}
public House (House similarHouse) {
//statements
}
public void setStyle (String theStyle) {
//statements
}
public void setLocation (String where) {
//statements
}
public void setPrice (String currentPrice) {
//statements
}
public String describe () {
//statements
}
public String code (String prefix) {
//statements
}
// instance variables
}