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

Slides:



Advertisements
Similar presentations
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
Advertisements

Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Introduction to Software Design Chapter 1. Chapter 1: Introduction to Software Design2 Chapter Objectives Intro - Software OOP Inheritance, interfaces,
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Programming Languages and Paradigms Object-Oriented Programming.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Object Oriented Programming
Introduction to Object-oriented programming and software development Lecture 1.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Data Structures and Algorithms in JAVA Chapter 2.
Data Abstraction: The Walls
Object-Oriented Programming
Inheritance and Polymorphism
Java Programming Language
Object-Oriented Programming
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Chapter 14 Abstract Classes and Interfaces
Presentation transcript:

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