450 likes | 472 Views
Chapter 1. OO Programming and Class Hierarchies. Chapter Objectives. OOP ADT's Inheritance, interfaces, abstract classes, overloading, overriding, etc. Polymorphism Exceptions. Key Programming and Design Issues. Modularity Modifiability Ease of use Fail-safe programming
E N D
Chapter 1 OO Programming and Class Hierarchies
Chapter 1: Introduction to Software Design Chapter Objectives • OOP • ADT's • Inheritance, interfaces, abstract classes, overloading, overriding, etc. • Polymorphism • Exceptions
Chapter 1: Introduction to Software Design Key Programming and Design Issues • Modularity • Modifiability • Ease of use • Fail-safe programming • Efficiency • Generality and Reusability
Chapter 1: Introduction to Software Design Achieving a Modular Design: • Abstraction • data – focuses on what operations do • procedural – separates the purpose of a method from the implementation • abstract data type (ADT) – a collection of data and a set of operations • Information hiding – limits the ways that data and methods can be accessed • Object Oriented Programming • Encapsulation • Inheritance • Polymorphism • Top-Down design • Focuses on the verbs (actions that are to be performed) • Identifies the things that need to be done, subdivides tasks, etc.
Chapter 1: Introduction to Software Design Common Design Flaws - OOP • Classes that make direct modification to other classes. • Weak within class cohesiveness, strong between class cohesiveness. • Classes with too much responsibility. • Classes with no responsibility. • Classes with unused responsibility. • Misleading Names. • Unconnected Responsibility. • Innapropriate use of inheritance. Relationship is not is-a, or class cannot inherit any useful behavior from super class. • Repeated functionality.
Chapter 1: Introduction to Software Design Another key programming issue - Style • Proper use of white space • Indentation of code blocks • Blank lines • Well-chosen identifiers • Class names – each word capitalized • Method names – first letter lower case, each word capitalized • Named constants – all upper case, underscores separate words • Method variables – all lower case • Object/class variables – append an underscore after the name • Documentation • see next page
Chapter 1: Introduction to Software Design Documentation • What is a comment? • What should a comment say? • Where do you need comments (for this class)? • every public/protected method. • @param • @return • @precondition • @postcondition • every class • every class member
Chapter 1: Introduction to Software Design A comment is text that is added to program code that is ignored by the compiler /* a multi-line comment */ /** Javadoc */ // single line comment See http://java.sun.com/j2se/javadoc/writingdoccomments/ http://www.time2help.com/doc/online_help/idh_java_doc_tag_support.htm A comment should describe What a program segment should do The circumstances under which it will do it You should have an opening comment for each class method
Chapter 1: Introduction to Software Design What’s a good comment? What’s a bad comment? What’s a neutral comment?
Chapter 1: Introduction to Software Design A good comment brings clarity public class Ratio { /* an object for storing a fraction like 2/3 */ A neutral comment is one doesn’t really help or hinder protected int numerator; // numerator of ratio A bad comment is one that is misleading public class Ratio { /* this class does whatever you want */
Chapter 1: Introduction to Software Design When do you write comments? • Comments should be created ASAP • Comments should not be added after the fact! • However, we all do this • Note: if you name your stuff (variables and methods) appropriately, you generally don’t need as many comments
Chapter 1: Introduction to Software Design Using Abstraction to Manage Complexity • An abstraction is a model of a physical entity or activity • Abstraction helps programmers deal with complex issues in a piecemeal fashion • Procedural abstraction: distinguish what is to be achieved by a procedure from its implementation • Data abstraction: specify the data objects for a problem and the operations to be performed on them without concern for their representation in memory
Chapter 1: Introduction to Software Design Using Abstraction to Manage Complexity (continued) • If a higher-level class references a data object only through its methods, the higher-level class will not have to be rewritten, even if the data representation changes • Information hiding: Concealing the details of a class implementation from users of the class
Chapter 1: Introduction to Software Design Abstract Data Types, Interfaces, and Pre- and Postconditions • A major goal of software engineering is to write reusable code • Abstract data type (ADT): The combination of data together with its methods • A Java interface is a way to specify an ADT • The interface specifies the names, parameters, and return values of the ADT methods without specifying how the methods perform their operations and without specifying how the data is internally represented • Each class that implements an interface must provide the definitions of all methods declared in the interface
Chapter 1: Introduction to Software Design Abstract Data Types, Interfaces, and Pre- and Postconditions (continued)
Chapter 1: Introduction to Software Design Abstract Data Types, Interfaces, and Pre- and Postconditions (continued) • You cannot instantiate an interface • You can declare a variable that has an interface type and use it to reference an actual object • A Java interface is a contract between the interface designer and the programmer who codes a class that implements the interface • Precondition: a statement of any assumptions or constraints on the method data before the method begins execution • Postcondition: a statement that describes the result of executing a method
Chapter 1: Introduction to Software Design Introduction to Inheritance and Class Hierarchies • Popularity of OOP is that it enables programmers to reuse previously written code saved as classes (extensible, encapsulation, polymorphism) • All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes • Inheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another
Chapter 1: Introduction to Software Design Is-a Versus Has-a Relationships • One misuse of inheritance is confusing the has-a relationship with the is-a relationship • The has-a relationship means that one class has the second class as an attribute • We can combine is-a and has-a relationships • The keyword extends specifies that one class is a subclass of another
Chapter 1: Introduction to Software Design A Superclass and a Subclass • Consider two classes: Computer and Laptop • A laptop is a kind of computer and is therefore a subclass of computer
Chapter 1: Introduction to Software Design Initializing Data Fields in a Subclass and the No-Parameter Constructor • Private data fields belonging to a base class must be initialized by invoking the base class’s constructor with the appropriate parameters • If the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclass • Initializes that part of the object inherited from the superclass before the subclass starts to initialize its part of the object
Chapter 1: Introduction to Software Design Protected Visibility for Superclass Data Fields • Private data fields are not accessible to derived classes • Protected visibility allows data fields to be accessed either by the class defining it or any subclass • In general, it is better to use private visibility because subclasses may be written by different programmers and it is always good practice to restrict and control access to the superclass data fields
Method Overriding • If a derived class has a method found within its base class, that method will override the base class’s method • The keyword super can be used to gain access to superclass methods overridden by the base class • A subclass method must have the same return type as the corresponding superclass method Chapter 1: Introduction to Software Design
Chapter 1: Introduction to Software Design Method Overloading • Method overloading: having multiple methods with the same name but different signatures in a class • Constructors are often overloaded • Example: • MyClass(int inputA, int inputB) • MyClass(int inputA, int inputB, double inputC)
Chapter 1: Introduction to Software Design Polymorphism • A variable of a superclass type can reference an object of a subclass type • Polymorphism means many forms or many shapes • Polymorphism allows the JVM to determine which method to invoke at run time • At compile time, the Java compiler can’t determine what type of object a superclass may reference but it is known at run time
Chapter 1: Introduction to Software Design Abstract Classes, Assignment, and Casting in a Hierarchy • An interface can declare methods but does not provide an implementation of those methods • Methods declared in an interface are called abstract methods • An abstract class can have abstract methods, data fields, and concrete methods • Abstract class differs from a concrete class in that • An abstract class cannot be instantiated • An abstract class can declare abstract methods, which must be implemented in its subclasses
Chapter 1: Introduction to Software Design Abstract Classes and Interfaces • Like an interface, an abstract class can’t be instantiated • An abstract class can have constructors to initialize its data fields when a new subclass is created • Subclass uses super(…) to call the constructor • May implement an interface but it doesn’t have to define all of the methods declared in the interface • Implementation is left to its subclasses
Chapter 1: Introduction to Software Design Summary of Features of Actual Classes, Abstract Classes, and Interfaces
Chapter 1: Introduction to Software Design Using Multiple Interfaces to Emulate Multiple Inheritance • If we define two interfaces, a class can implement both • Multiple interfaces emulate multiple inheritance
Chapter 1: Introduction to Software Design Run-time Errors or Exceptions • Run-time errors • Occur during program execution • Occur when the JVM detects an operation that it knows to be incorrect • Cause the JVM to throw an exception • Examples of run-time errors include • Division by zero • Array index out of bounds • Number format and Input mismatch error • Null pointer exceptions
Chapter 1: Introduction to Software Design Run-time Errors or Exceptions (continued)
Chapter 1: Introduction to Software Design Logic Errors • A logic error occurs when the programmer or analyst • Made a mistake in the design of a class or method • Implemented an algorithm incorrectly • Most logic errors do not cause syntax or run-time errors and are thus difficult to find • Sometimes found through testing • Sometimes found during real-world operation of the program
Chapter 1: Introduction to Software Design The Exception Class Hierarchy • When an exception is thrown, one of the Java exception classes is instantiated • Exceptions are defined within a class hierarchy that has the class Throwable as its superclass • Classes Error and Exception are subclasses of Throwable • RuntimeException is a subclass of Exception
Chapter 1: Introduction to Software Design The Class Throwable • Throwable is the superclass of all exceptions • All exception classes inherit the methods of throwable
Chapter 1: Introduction to Software Design The Class Throwable (continued)
Chapter 1: Introduction to Software Design Checked and Unchecked Exceptions • Two categories of exceptions: checked and unchecked • Checked exception normally not due to programmer error and is beyond the control of the programmer • Unchecked exception may result from • Programmer error • Serious external conditions that are unrecoverable
Chapter 1: Introduction to Software Design Checked and Unchecked Exceptions
Chapter 1: Introduction to Software Design Catching and Handling Exceptions • When an exception is thrown, the normal sequence of execution is interrupted • Default behavior • Program stops • JVM displays an error message • The programmer may override the default behavior by • Enclosing statements in a try block • Processing the exception in a catch block
Chapter 1: Introduction to Software Design Uncaught Exceptions • When an exception occurs that is not caught, the program stops and the JVM displays an error message and a stack trace • The stack trace shows the sequence of method calls, starting at the method that threw the exception and ending at main
Chapter 1: Introduction to Software Design The try-catch-finally Sequence • Avoid uncaught exceptions • Write a try-catch sequence to catch an exception • Handle it rather than relying on the JVM • Catch block is skipped if all statements within the try block execute without error
Chapter 1: Introduction to Software Design Handling Exceptions to Recover from Errors • Exceptions provide the opportunity to • Recover from errors • Report errors • User error is a common source of error and should be recoverable • Catch block within the first catch clause having an appropriate exception class executes, others are skipped • Compiler displays an error message if it encounters an unreachable catch clause
Chapter 1: Introduction to Software Design The finally Block • When an exception is thrown, the flow of execution is suspended and there is no return to the try block • There are situations in which allowing a program to continue after an exception could cause problems • The code in the finally block is executed either after the try block is exited or after a catch clause is exited • The finally block is optional
Chapter 1: Introduction to Software Design Throwing Exceptions • Instead of catching an exception in a lower-level method, it can be caught and handled by a higher-level method • Declare that the lower-level method may throw a checked exception by adding a throws clause to the method header • Can throw the exception in the lower-level method, using a throw statement • The throws clause is useful if a higher-level module already contains a catch clause for this exception type
Chapter 1: Introduction to Software Design Throwing Exceptions (continued) • Can use a throw statement in a lower-level method to indicate that an error condition has been detected • Once the throw statement executes, the lower-level method stops executing immediately
Chapter 1: Introduction to Software Design Catching Exceptions Example