320 likes | 450 Views
B Smith: Sp08: rate: 3, time: 60 minutes since there was still confusion regarding the schedule. Redo this by hand to bring more to life. Designing Classes. Math 140 Data Structures and Algorithms Lecture # 3 Tuesday, Jan. 22, 2008. Objectives.
E N D
B Smith: Sp08: rate: 3, time: 60 minutes since there was still confusion regarding the schedule. Redo this by hand to bring more to life Designing Classes Math 140Data Structures and Algorithms Lecture # 3 Tuesday, Jan. 22, 2008
Objectives • Describe encapsulation (information hiding), and data abstraction • Write specifications for methods that include preconditions and postconditions • Write a Java interface for a class • Choose appropriate classes and methods during the design of a program, including classes that might be written already
B Smith: why oop and software engineering E. W. Dijkstra • “The Cruelty of Really Teaching Computer Science” • “The End of Computing Science”
Encapsulation • Hides the fine details of the inner workings of the class • The implementation is hidden • The class interface is made visible • The programmer is given only enough information to use the class • think sun Java API
Encapsulation Fig. 3-1 An automobile's controls are visible to the driver, but its inner workings are hidden.
Abstraction • A process that has the designer ask what instead of how • What is it you want to do with the data • What will be done to the data • The designer does not consider how the class's methods will accomplish their goals • The client interface is the what • The implementation is the how
Abstraction Fig. 3-2 An interface provides well-regulated communication between a hidden implementation and a client.
Specifying Methods: Pre/Post Cond. • Specify what each method does • Precondition • Defines responsibility of client code • Postcondition • Specifies what will happen if the preconditions are met
B Smith: this one needs to be explained carefully or deleted. Specifying Methods: Responsibility • Responsibility • Precondition implies responsibility for guarantee of meeting certain conditions • Where to place responsibility • Client? or … • Method? • Best to comment this clearly before method's header • Also good to have method check during debugging
Specifying Methods: Assertions • Assertion is statement of truth about aspect of a program's logic • Like a boolean statement that should be true at a certain point • Assertions can be written as comments to identify design logic// Assertion: intVal >= 0 • Assert Statement • assert someVal < 0; • If false, program execution terminates
Java Interface • A program component that contains • Public constants • Signatures for public methods • Comments that describe them • Begins like a class definition • Use the word interface instead of classpublic interface someClass{ public int someMethod();}
Writing an Interface • Consider geometric figures which have both a perimeter and an area • We want classes of such objects to have certain methods • And we want standard signatures • View example of the interface Measurable
Java Interface Example • Recall class Namefrom previous chapter • Consider an interface for the class Name • View example listing • Note • Comments of method purpose, parameters, pre- and post-conditions • Any data fields should be public, final, and static • Interface methodscannot be final
Java Interface Example public interface NameInterface { /** Task: Sets the first and last names. * @param firstName a string that is the desired first name * @param lastName a string that is the desired last name */ public voidsetName(String firstName, String lastName); /** Task: Gets the full name. * @return a string containing the first and last names */ publicString getName(); public voidsetFirst( String firstName );publicString getFirst(); public voidsetLast( String lastName );publicString getLast(); public voidgiveLastNameTo( NameInterface child ); publicString toString(); }
Implementing an Interface • A class that implements an interface must state so at start of definitionpublic class myClass implements someInterface • The class must implement every method declared in the interface • Multiple classes can implement the same interface • A class can implement more than one interface • public void someMethod (someInterface x)
Implementing an Interface Fig. 3-3 The files for an interface, a class that implements the interface, and the client.
An Interface as a Data Type • An interface can be used as a data typeor …
Generic Types Within an Interface • Recall class OrderedPair • Note the setPair method • Consider an interface Pairable that declares this method A class that implements this interface could begin with the statement
The Interface Comparable • Method compareTo compares two objects, say x and y • Returns signed integer • Returns negative if x < y • Returns zero if x == y • Returns positive if x > y
The Interface Comparable • Consider a class Circle • Methods equals, compareTo • Methods fromMeasurable • View source code • Note • Implements Measurable interface • Shown with two alternative versions of compareTo
Extending an Interface • Use inheritance to derive an interface from another • When an interface extends another • It has all the methods of the inherited interface • Also include some new methods • Also possible to combine several interfaces into a new interface • Not possible with classes
Interfaces Versus Abstract Classes • Purpose of interface similar to purpose of abstract class • But … an interface is not a base class • It is not a class of any kind • Use an abstract base class when • You need a method or private data field that classes will have in common • Otherwise use an interface
Named Constants Within an Interface • An interface can contain named constants • Public data fields initialized and declared as final • Consider an interface with a collection of named constants • Then derive variety of interfaces that can make use of these constants
B Smith: Students did not need a thorough review. Spend 10 minutes reviewing. Exception Handling Appendix B Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple" cases
Exception Handling Overview • A way of organizing a program into sections for the normal case and the exceptional case • exception examples:division by zeroincorrect type of input • A way of implementing programs incrementally • code for normal operation first • exceptional case later • Simplifies development, testing, debugging and maintenance • errors are easier to isolate
Some Terminology • Throwing an exception: either Java itself or your code signals when something unusual happens • Handling an exception: responding to an exception by executing a part of the program specifically written for the exception • also called catching an exception • The normal case is handled in a try block • The exceptional caseis handled in a catchblock • The catch block takes a parameter of type Exception • it is called the catch-blockparameter • e is a commonly used name for it • If an exception is thrown execution in the try block ends and control passes to the catch block(s) after the try block
try-throw-catchTriplet Basic code organization: try { <code to try> if(test condition) throw new Exception("Message to display"); <more code> } catch(Exception e) { <exception handling code> } <possibly more code>
B Smith: spent time on a student error where “new” was not used. An Example of Exception Handling ExceptionDemo try and catch blocks try block throw statement catch block 40 Chapter 8 Java: an Introduction to Computer Science & Programming - Walter Savitch
More about the catch-Block The catch-block is not a method definition! Every Exception has a getMessage method • throw new Exception("This message is retrieved");
Predefined Exception Classes • Exception is the root class of all exceptions • Many predefined classes throw exceptions • the documentation or interface will tell you • the exceptions thrown are often also predefined • Some common predefined exceptions: • IOException • ClassNotFoundException, and • FileNotFoundException
Code Organization when Using an Object that May Throw an Exception Sample object = new SampleClass(); try { <Possibly some code> object.doStuff(); //may throw IOException <Possibly some more code> } catch(IOException e) { <Code to handle the IOException, probably including this line:> System.out.println(e.getMessage()); } • Predefined exceptions usually include a meaningful message that is retrieved with getMessage
Defining Your Own Exception Classes public class DivideByZeroException extends Exception { public DivideByZeroException() { super("Dividing by Zero!"); } public DivideByZeroException(String message) { super(message); } } • Must be derived from some already defined exception class • Often the only method you need to define is the constructor • Include a constructor that takes a String message argument • Also include a default constructor with a call to super and default message string For example Display 8.3/page 417