Top Banner
Object Oriented Design
45

Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

Dec 29, 2015

Download

Documents

Jonah Mathews
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

Object Oriented Design

Page 2: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 3: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 4: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 5: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

Object Oriented Design Principles

• Abstraction• Encapsulation• Modularity

Page 6: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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.

Page 7: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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();

Page 8: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

Java language constructs support OOD

• Interface: supports procedural abstraction• Class: supports encapsulation

Page 9: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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.

Page 10: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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);

}

Page 11: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 12: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

Interfaces

• See• Sortable.java (interface)• Person.java (class implementing Sortable interface)• Sorter.java (a generic sorter)• SorterDriver.java (driver to test Sorter)

Page 13: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 14: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 15: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 16: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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)

Page 17: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

OOD provides ways of reusing code

• Inheritance: • modular and hierarchical organizing structure

• Method overriding• Polymorphism

Page 18: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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.

Page 19: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 20: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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()

Page 21: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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 + “]”;

}

}

Page 22: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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 superclasscenter = 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 + “]”;

}}

Page 23: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 24: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 25: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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()

Page 26: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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.

Page 27: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 28: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 29: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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]);

Page 30: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 31: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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.

}

Page 32: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

public class Circle extends Shape {

… public void draw() {

//Circle drawing code goes here}

…}

Page 33: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 34: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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.

Page 35: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 36: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

The Class Throwable• All exception classes inherit the methods of Throwable

Page 37: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 38: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 39: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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 exceptionstatements 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}

Page 40: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

} } }

Page 41: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 42: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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

Page 43: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

methodA( {try {

methodB();}

catch (IOException e) { System.out.println(e.getMessage()); }}

methodB() throws IOException{ // some File operation that may throw and IOException}

Page 44: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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();

}

Page 45: Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.

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);

}

}