1 / 32

Designing Classes

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.

corina
Download Presentation

Designing Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. B Smith: why oop and software engineering E. W. Dijkstra • “The Cruelty of Really Teaching Computer Science” • “The End of Computing Science”

  4. 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

  5. Encapsulation Fig. 3-1 An automobile's controls are visible to the driver, but its inner workings are hidden.

  6. 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

  7. Abstraction Fig. 3-2 An interface provides well-regulated communication between a hidden implementation and a client.

  8. 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

  9. 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

  10. 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

  11. 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();}

  12. 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

  13. 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

  14. 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(); }

  15. 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)

  16. Implementing an Interface Fig. 3-3 The files for an interface, a class that implements the interface, and the client.

  17. An Interface as a Data Type • An interface can be used as a data typeor …

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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

  24. 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

  25. 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

  26. 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

  27. 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>

  28. 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

  29. 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");

  30. 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

  31. 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

  32. 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

More Related