460 likes | 570 Views
Object Oriented Design. OOP. Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java programs are organized around the notion of hierarchy of objects and classes. Objects. An object is an entity which Stores data --- state
E N D
OOP • Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other • Java programs are organized around the notion of hierarchy of objects and classes
Objects • An object is an entity which • Stores data ---state • Can perform actions --- behavior • A Java program works by having objects perform actions • An object is an instance of a class • instance variables – data • methods -- actions
OOD Goals • Robustness • Correct • Can handle unusual/error cases gracefully • Adaptability – evolvability • Portability • Reusability • Same code can be a component of diffferent systems in various applications
Object Oriented Design Principles • Abstraction • Encapsulation • Modularity
Abstraction • Provides high-level model of a physical entity or activity • Procedural abstraction: • Specify what is to be achieved by a procedure • Hide algorithms • Data abstraction: • specify the data objects for a problem • without concern for their representation in memory • The designer can focus on how to use the data objects and their actions rather than low-level details of their implementation.
Encapsulation • Combine data elements and methods in a class and confine information so that it is only visible/accessible through an associated external interface (public methods in Java) • Information hiding: Concealing the details of a class implementation from users of the class • 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 or method implementation changes. • e.g. • myEntry.name • myEntry.firstName + myEntry.lastName; • MyEnrty.getFullName();
Java language constructs support OOD • Interface: supports procedural abstraction • Class: supports encapsulation
Abstract Data Types • Abstract data type (ADT): The combination of data together with its methods • what of the data structure, • NOT “how” of the data structure • E.g. Stack ADT? • Data? • Operations? • The primary goal of this class is to teach you how to use ADTs and how to create their implementations. • Also, you will be introduced to Java API’s ADTs.
Interfaces • 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 • May also contain constant definitions public interface Comparable { public int compareTo(Object o); }
Interfaces • A Java interface is a contract between the interface designer and the programmer who codes a class that implements the interface • Each class that implements an interface must provide the definitions of all methods declared in the interface public class SomeClass implements Comparable {…} • Classes specify how the operations are performed in the body of each method
Interfaces • See • Sortable.java (interface) • Person.java (class implementing Sortable interface) • Sorter.java (a generic sorter) • SorterDriver.java (driver to test Sorter)
Modularity • An organizing principle for code in which different components of a software system are divided into separate functional units • Helps software reusability • E.g. A module of vector and matrix operations are frequently used in geometric programming and graphics applications
Design Patterns • Designing good code requires effective use of OOD techniques • A variety of organizational concepts and methodologies have been developed • Special relevance to this class: Design Pattern • describes a solution to a typical software design problem • Provides a general template for a solution that can be applied in many different situations • Describes the main elements of a solution in an abstract way
Design Patterns • A design pattern consists of • A name • A context: describes scenarious in which this pattern can be applied • A template: describes how the pattern is applied • A result: describes and analyzes what the pattern produces
Design patterns • Some patterns for solving algorithm design problems • Recursion • Amortization • Divide-and-conquer • Some patterns for solving software engineering problems • Position • Adapter • Iterator • Composition • Comparator • Decorator • MVC (Model-View-Controller)
OOD provides ways of reusing code • Inheritance: • modular and hierarchical organizing structure • Method overriding • Polymorphism
Inheritance and Class Hierarchies • Popularity of OOP is that it enables programmers to reuse previously written code saved as classes • 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 • Inheritance is the process by which a new class called the subclass is created from another class called the superclass.
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
Shape, Circle, Rectangle • Consider one superclass: Shape • Two subclasses: Circle, Rectangle • Store code and data that is common to all subclasses in the superclass, Shape: • color • getColor() • setColor() • Circle and Rectangle inherit all the instance variables and the methods that Shape has. • Circle and Rectangle are allowed to define new instance variables and new methods that are specific to them. Circle: • center, radius • getArea(), getPerimeter()
Shape class public class Shape { private String color; public Shape() { color = “red”; } public String getColor() { return color}; public String setColor( String newColor) { color = newColor; } public String toString() { return “[“ + color + “]”; } }
public class Circle extends Shape { public static final double PI = 3.14159; private Point center; private double radius; public Circle() { super(); // calls the constructor of the superclass center = new Point(0,0,0); radius = 1.0; } public double getArea() { return PI * radius * radius; } public double getPerimeter() { return 2 * PI * radius; } public String toString() { return super.toString() + “[“ + center + “,” + radius + “]”; } }
Initializing Data Fields in a Subclass and the No-Parameter Constructor • Private data fields belonging to a superclass must be initialized by invoking the superclass’s constructor with the appropriate parameters super(…) • It has to be the first statement in the constructor • 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
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. E.g. if we define color in Shape class as: protected String color; It is directly accessible from Circle and Rectangle and any other derived classes. • 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 subclass has a method found within its superclass, that method will override the superclass’s method toString() is overridden in Circle • The keyword super can be used to gain access to superclass methods overridden in the subclass. super.toString()
Is-a Versus Has-a Relationships • Inheritance defines a is-a relationship • Laptop is-a Computer • Circle is-a Shape • Shape is-a Object • 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 • e.g. Circle class has-a Point instance variable, center. Point is another class.
Polymorphism • Suppose you are not sure whether a shape referenced in a program is a Circle or Rectangle. • How can this situation arise? • If you declare the variable as a Shape type you can use it to reference an object of either type. • A variable of a superclass type can reference an object of a subclass type Shape s; s = new Circle(); //circle is a shape
Polymorphism • Polymorphism allows the JVM to determine which method to invoke at run time System.out.println(s.toString()); will invoke the toString() method of the Circle class, since s references a Circle object. • At compile time, the Java compiler cannot determine what type of object a superclass may reference but it is known at run time • Late (Dynamic) Binding
Polymorphism • Lets a single reference variable refer to objects of many different types. What type is shapeArray[i]?? Shape[] shapeArray = new Shape[3]; shapeArray[0] = new Circle(); shapeArray[1] = new Rectangle(); shapeArray[2] = new Oval(); for (int i =0; i < shapeArray.length; i++) System.out.println(shapeArray[i]);
draw() method in Shape class??? Shape[] shapeArray = new Shape[3]; shapeArray[0] = new Circle(); shapeArray[1] = new Rectangle(); shapeArray[2] = new Oval(); for (int i =0; i < shapeArray.length; i++) shapeArray[i].draw(); • The Shape class does not represent a specific shape. How do we implement its draw method?? • For the above code to compile, Shape class needs a draw() method
Abstract Classes • Let the compiler know that Shape is an abstract class: declares but does not implement some methods. • An abstract class can have abstract methods, data fields, and concrete methods • Abstract method: a method with no body. The subclass class will provide its actual implementation. public abstract class Shape { … public abstract void draw(); // derived classes will define their draw methods. … }
public class Circle extends Shape { … public void draw() { //Circle drawing code goes here } … }
Abstract Classes • An abstract class cannot be instantiated: • new Shape() is not allowed. • An abstract class can have constructors to initialize its data fields when a new subclass is created. • 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
Exceptions • A program often encounters problems as it executes. It may have trouble reading data, there might be illegal characters in the data, or an array index might go out of bounds.
Exceptions • An exception is a problem that occurs when a program is running. When an exception occurs, the Java virtual machine creates an object of class Exception which holds information about the problem. • Exceptions are defined within a class hierarchy that has the class Throwable as its superclass • Classes Error and Exception are subclasses of Throwable • We focus on Exception class and its descendants
The Class Throwable • All exception classes inherit the methods of Throwable
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
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
The try-catch-finally Sequence • Write a try-catch sequence to catch an exception • Handle it rather than relying on the JVM try { statements that may throw an exception statements that should not execute if an exception is thrown } catch (Exception e) { statements to handle the exception e } <other catch blocks> finally { statements executed no matter what }
import java.lang.* ; import java.io.* ; public class Square { public static void main ( String[] args ) throws IOException { BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) ); String inData; int num ; System.out.println("Enter an integer:"); inData = stdin.readLine(); try { num = Integer.parseInt( inData ); System.out.println("The square of " + inData + " is " + num*num ); } catch(NumberFormatException e) { System.out.println("You entered bad data." ); System.out.println("Run the program again." ); } finally { System.out.println("Good-bye" ); } } }
try-catch-finally • Catch block is skipped if all statements within the try block execute without error • Catch block within the first catch clause having an appropriate exception class executes, others are skipped
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
methodA( { try { methodB(); } catch (IOException e) { System.out.println(e.getMessage()); } } methodB() throws IOException { // some File operation that may throw and IOException }
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. Exception is thrown out to the caller of the method. methodB() throws MyException { throw new MyException(); }
Which exception to throw? • An already defined Java Exception • OR, write your own Exception class public class MyException extends Exception { public MyException() { super(“Default Message for MyException”); } public MyException(String message) { super(message); } }