CSE 501N Fall ‘09 06: Data Abstraction & Design

Slides:



Advertisements
Similar presentations
Fields, Constructors, Methods
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Road Map Introduction to object oriented programming. Classes
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Classes, Encapsulation, Methods and Constructors
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Object Oriented Software Development
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
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.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Introduction to Java Java Translation Program Structure
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© 2004 Pearson Addison-Wesley. All rights reserved September 12, 2007 Encapsulation ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
1 Object-Oriented Design Now we can extend our discussion of the design of classes and objects Chapter 6 focuses on: software development activities determining.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2004 Pearson Addison-Wesley. All rights reserved October 31, 2007 Static Class Members ComS 207: Programming I (in Java) Iowa State University, FALL.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Object-Oriented Design
Chapter 3: Using Methods, Classes, and Objects
Creating Objects & String Class
Chapter 4: Writing Classes
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Chapter 5 – Writing Classes
Defining Your Own Classes Part 1
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Chapter 4: Writing classes
Chapter 6 Methods: A Deeper Look
IFS410: Advanced Analysis and Design
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Chapter 4 Writing Classes.
Static Class Members March 29, 2006 ComS 207: Programming I (in Java)
CS139 October 11, 2004.
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object Oriented Programming Review
Encapsulation September 13, 2006 ComS 207: Programming I (in Java)
Java Programming Language
Defining Classes and Methods
Chap 2. Identifiers, Keywords, and Types
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Object-Oriented Design Part 2
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

CSE 501N Fall ‘09 06: Data Abstraction & Design 15 September 2009 Nick Leidenfrost

Lecture Outline Conditional Statements Revisited The this keyword else if The switch statement The conditional ternary The this keyword Program design Class relationships Design Exercises

Review: if / else Conditional statements allow us to conditionally execute statements Based on value of boolean expressions if ( conditional ) { // Statements } else { if ( conditional ) { // Statements } if ( conditional ) // Statement

else if An if statement can be used as the statement executed by an else clause if (count == 0) { // Statements } else if (count < 0) { else { if (count == 0) { // Statements } else if (count < 0) {

Multiple Cases if / else statements can be ‘chained together’ to test for multiple cases if (count == 0) { // Statements } else if (count == 1) { else if (count == 2) { else if (count == 3) { …

The switch Statement The switch statement evaluates an expression, then attempts to match the result to one of several possible cases The switch statement can be used to replace long chains of else if conditions

Syntax: switch The general syntax of a switch statement is: switch and case are reserved words switch ( expression ) { case value1: statement-list1 case value2: statement-list2 case value3: statement-list3 case ... } If the result of expression matches value2, control jumps to here The values held by case statements must be constant expressions (not variables)

The switch Statement The implicit boolean condition in a switch statement is equality (==) The expression of a switch statement must result in an integral type, meaning an int Okay: int, short, char, enum* Assignable to int Not okay: long It cannot be a boolean value, a floating point value (float or double) You cannot perform relational checks with a switch statement

The switch Statement Often a break statement is used as the last statement in a case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

Error: Unreachable Statement The switch Statement A switch statement with break: switch (count) { case 0: zeroCount++; break; case 1: oneCount++; case 2: twoCount++; doSomething(); } Error: Unreachable Statement

The default case is traditionally last, but does not have to be last The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch The default case is traditionally last, but does not have to be last switch (value) { case 1: doSomething(); break; case 2: doSomethingElse(); break; default: eatIceCream(); }

The ternary operator Allows for quick, one line conditional execution Best for conditional assignments Conditional (predicate) Statement to execute if true double max = (valueOne > valueTwo) ? valueOne : valueTwo; Statement to execute otherwise

The this Reference me, myself, and I The this reference allows an object to refer to itself Think of this as a variable that refers to the currently executing object We can interact with the this reference in almost the same way as any other object variable We can perform assignments, supply this as the actual parameter of a method invocation, or use the dot operator to reference / invoke fields and methods Exception: This cannot be used as the left-hand side of an assignment. this = new BankAccount(1000, 500.0);

The this Reference Typically, this is used when referencing instance variables, or the object itself inside methods this can also be used to invoke methods on the object public class BankAccount { public void withdraw (double amount) { if (amount > this.balance) this.borrowMoney(amount); this.balance -= amount; } public class BankAccount { public void withdraw (double amount) { this.balance -= amount; }

The this Reference Self-Commenting Code this can also help to increase the readability of our code When another programmer sees a variable referenced with this and the dot operator, it is immediately evident that the variable is an instance variable We don’t have to search for a local variable declaration, we know immediately what we are interacting with public class BankAccount { public void withdraw (double amount) { this.balance -= amount; }

The this Reference public void withdraw (double amount) { this.balance -= amount; } account1.withdraw(500); account2.withdraw(10); In the first invocation, the this reference refers to account1, in the second it refers to account2 this is often used to supply the “current” object as a parameter // Inside a method of the BankAccount class bank.awardInterest(this);

The this reference Removing Ambiguity The this reference can also be used to distinguish the instance variables of a class from corresponding method parameters with the same names The constructor of the BankAccount class could have been written as follows: The this keyword used with the dot operator tells Java that we are referring to the instance variable name Notice that the name of the formal parameter is the same as the name of the instance variable. protected String name; protected double balance; public BankAccount (String name, double balance) { this.name = name; this.balance = balance; }

What is the end result of these assignments? The this reference When a local variable (or formal parameter) has the same name as an instance variable, Java chooses the variable that is most relevant to the context The local variable is used This can cause very subtle problems: What is the end result of these assignments? protected String name; protected double balance; public BankAccount (String name, double balance) { name = name; balance = balance; }

Designing Software Object-Oriented Design Although there are established styles and paradigms for object-oriented design, the practice as a whole is subjective No absolute right and wrong way Kind of like writing an essay… One approach to OO Design is Top-Down First identify high-level entities in the program What attributes do the entities have? (state) How should the entities interact to manipulate that state? (behavior)

Designing Software Identifying High Level Entities The core activity of object-oriented design is determining the classes and objects that will make up the solution The classes that comprise our solution may be part of a class library, reused from a previous project, or newly written One way to identify potential classes is to identify the objects discussed in the requirements Objects are generally nouns, and the services (behavior) that an object provides are generally verbs

Identifying Classes and Objects …From a Formal Requirements Document A partial requirements document: Of course, not all nouns will correspond to a class or object in the final solution, but this generally a good way to get an initial breakdown of the classes in a design. The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A.

Identifying Classes and Objects Determining Class Granularity Sometimes it is challenging to decide whether something should be represented as a class For example, should an Employee's address be represented as a set of instance variables or as an Address object The more you examine the problem and its details the more clear these issues become Is functionality that would be in this class reusable? Can this class provide functionality for two or more uses? Do the interactions of this functionality obscure the purpose of the class that is using it?

Identifying Classes and Objects Determining Class Granularity When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities public class Employee { protected String address1, address2; protected String city, state, zipcode; public String getAddressLineOne () { return address1; } public String setAddressLineOne (String address1) { this.address1 = address1; } ...

Identifying Classes and Objects Determining Class Granularity When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities public class Employee { protected Address address; public String getAddress () { return address; } public String setAddress (Address address) { this.address = address; public class Address { protected String address1, address2; protected String city, state, zipcode; public String getAddressLineOne () { return address1; } public String setAddressLineOne (String address1) { this.address1 = address1; } ...

Identifying Classes and Objects The Appropriate Level of Detail / Abstraction We want to define classes with the proper amount of detail For example, let’s say we want to design a program to control the various systems of a house it may be unnecessary to create separate classes for each type of appliance in a house It may be sufficient to define a more general Appliance class with appropriate instance data It all depends on the details of the problem being solved

Identifying Attributes We know that classes often mimic real-world entities and the instance variables that define the state typically model attributes of the real world entity What attributes do we care about in our program? What attributes are unimportant? Is the attribute something that is transient, e.g., not actually stored in an instance variable, but calculated from other attributes? E.g. the GPA of a Student

Identifying Behavior Every activity that a program must accomplish must be represented by one or more methods in one or more classes Generally, methods get verbs for names Or short verb-oriented phrases We should start to think about: What behavior should be accessible to other classes and their objects (public) What behavior should be more closely guarded (private, default (package protected), protected) In early stages it is not necessary to determine every method of every class – begin with primary responsibilities and evolve the design

Class Relationships Classes in a software system can have various types of relationships to each other Three of the most common relationships: Dependency: A uses B Aggregation: A has-a B Inheritance: A is-a B

Dependency I Need You. A dependency exists when one class relies on another in some way, by referencing the fields or invoking the methods of the other: Our Calculator class from Lab 1 depends on the Math object public double exp (double a, double b) { return Math.pow(a, b); }

Balancing Dependency A Two-Sided Blade Numerous / complex dependencies among classes Dependencies should use methods as much as possible Dependency on implementation specific entities (instance variables) creates susceptibility to change Example: GPA Classes that don't depend on others Forces us to reinvent functionality Role or purpose of class would not be as clear Muddied by code that is not central to the purpose of the class A good design strikes the right balance

Aggregation You Complete Me. An aggregate is an object that is made up of other objects Therefore aggregation is a has-a relationship A car has-a chassis In software, an aggregate object contains references to other objects as instance variables The aggregate object is defined in part by the objects that make it up This is a special kind of dependency – the aggregate usually relies on the objects that compose it

Aggregation For example, a Student object is composed, in part, of Address objects A student has an address (in fact each student probably has two addresses) [Example on the board]

Inheritance We’re Practically Related. Inheritance allows us to use an existing, more generalized, class to create more specific functionality Leverages existing functionality Reduces code duplication Allows for polymorphism Much more on this later…

Data Abstraction Hey! Don’t touch that! Enforcement of clear separation between Abstract properties of a data type (class) and Concrete details of its implementation What does this mean?

Data Abstraction Defining the Granularity of Interaction A separation between what is publicly viewable and what is encapsulated Decide what other entities should be able to access / manipulate Use access modifiers and packages to define encapsulation Define accessor and mutator methods to define access / manipulation of state What is publicly viewable in a data type? Typically a subset of its methods On occasion certain public variables or constants

ADT Exercises Bank Account Football League A Card Game

Questions? Lab 2 will be assigned on Wednesday Lab 1.5 due by Midnight Lab now in Sever 201