Chapter 8: Designing Classes

Slides:



Advertisements
Similar presentations
Chapter 8 Designing Classes Designing Classes –8.1 Choosing Classes –8.2 Cohesion and Coupling –CRC Cards –UML Diagrams.
Advertisements

1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Based on Java Software Development, 5th Ed. By Lewis &Loftus
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
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.
Designing Classes Chapter 8. Classes Collection of objects Objects are not actions Class names – Nouns Method names – Verbs What Makes a Good Class Represent.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
Chapter 9 Designing Classes. Chapter Goals To learn how to choose appropriate classes to implement To understand the concepts of cohesion and coupling.
Chapter Goals To learn how to choose appropriate classes to implement
Road Map Introduction to object oriented programming. Classes
Chapter 7 Designing Classes Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling  To.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Class Design CSC 171 FALL 2004 LECTURE 11. READING Read Chapter 7 It’s abstract But it should help with project #1.
Using Objects Object: an entity in your program that you can manipulate Attributes Methods Method: consists of a sequence of instructions that can access.
Computer Science A 8: 6/3. Group data in an object class PlayerData{ String name; int score; }.. PlayerData d=new PlayerData(); d.name=“Mads”; d.score=100;
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
CSS446 Spring 2014 Nan Wang.  To learn how to choose appropriate classes for a given problem  To understand the concept of cohesion  To minimize dependencies.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 8 – Designing Classes.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
Week 12 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 8 – Designing Classes.
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Classes All Java code must be inside classes Class types – Utility classes Used to store constants, utility methods, etc. – Driver classes – Abstract Data.
ICOM 4015: Advanced Programming Lecture 8 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Eight:
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain Name.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 8 – Designing Classes.
CH 8 : Enhancing Classes - Review QUICK REVIEW : A Class defines an entity’s (Object’s) data and the actions or behaviors (Methods) associated with that.
Static. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A static method does not operate on an object double dY.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eight: Designing Classes.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain, or a.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Objects and Classes.
12 OBJECT-ORIENTED DESIGN CHAPTER
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and.
Chapter 8 – Designing Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 9 – Designing Classes Goals Learning to design classes Learning to design classes Preconditions and postconditions for methods Preconditions.
Chapter 7 Designing Classes. Chapter Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling.
Fall 2006Adapded from Java Concepts Slides1 Designing Classes Advanced Programming ICOM 4015 Lecture 8 Reading: Java Concepts Chapter 8.
Topics Instance variables, set and get methods Encapsulation
Chapter 9 – Designing Classes. Chapter Goals Discovering and learning to Design classes Discovering and learning to Design classes Preconditions and postconditions.
Chapter 3 Implementing Classes
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Chapter 8 – Designing Classes
CSSE 220 Day 17 Introduction to your Vector Graphics project
Chapter 8 Designing Classes
Lecture 7 Designing Classes
Implementing Classes Yonglei Tao.
7 CHAPTER OBJECTS AND CLASSES.
Chapter Three - Implementing Classes
Chapter 8 – Designing Classes
Chapter 8 – Designing Classes
JAVA CLASSES.
OO Programming Concepts
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Chapter 8: Designing Classes

Chapter Goals To learn how to choose appropriate classes to implement To understand the concepts of cohesion and coupling To minimize the use of side effects To understand the difference between instance methods and static methods To introduce the concept of static fields To understand the scope rules for local variables and instance fields To learn about packages

A class represents a single concept from the problem domain Choosing Classes A class represents a single concept from the problem domain Name for a class should be a noun that describes the concept Concepts from mathematics: Point Rectangle Ellipse Concepts from real life: BankAccount CashRegister Method names should be verbs. e.g. print, draw, sort,…

Choosing Classes Actors (ending in -er, -or) – are objects that do some kinds of work for you. e.g. Scanner Random // better name: RandomNumberGenerator Utility classes – not objects, only static methods and constants Math Program starters: only have a main method Don't turn actions into classes: Paycheck is a better name than ComputePaycheck

What classes would you use for the following problem description: Users place coins in a vending machine and select a product by pushing a button. If the inserted coins are sufficient to cover the purchase price of the product, the product is dispensed and change is given. Otherwise, the inserted coins are returned to the user. Answer: We might wish to make each of the following into classes: User VendingMachine Button Coin Product

Self Check 8.2 Your job is to write a program that plays chess. Might ChessBoard be an appropriate class? How about MovePiece? Answer: ChessBoard would be reasonable, but not MovePiece.

Cohesion A class should represent a single concept The public interface of a class is cohesive if all of its features are related to the concept that the class represents This class lacks cohesion: public class CashRegister { public void enterPayment(int dollars, int quarters, int dimes, int nickels, int pennies) . . . public static final double NICKEL_VALUE = 0.05; public static final double DIME_VALUE = 0.1; public static final double QUARTER_VALUE = 0.25; . . . } This class represents both the concept of a cash register, along with the concept of the value of coins (and these values are specific to North America)

Solution: Make two classes: Cohesion CashRegister, as described above, involves two concepts: cash register and coin Solution: Make two classes: public class Coin { public Coin(double aValue, String aName) { . . . } public double getValue() { . . . } . . . } public class CashRegister { public void enterPayment(int coinCount, Coin coinType) { . . . } . . . }

Coupling A class depends on another if it uses objects of that class CashRegister depends on Coin to determine the value of the payment Coin does not depend on CashRegister High Coupling = many class dependencies Minimize coupling to minimize the impact of interface changes To visualize relationships draw class diagrams UML: Unified Modeling Language. Graphical notation for object-oriented analysis and design

Coupling

High and Low Coupling Between Classes

Self Check 8.4 Why does the Coin class not depend on the CashRegister class? Answer: None of the coin operations require the CashRegister class.

Self Check 8.5 Why should coupling be minimized between classes? Answer: If a class doesn't depend on another, it is not affected by interface changes in the other class.

Accessors, Mutators and Immutable Classes Accessor: does not change the state of the implicit parameter double balance = account.getBalance(); Mutator: modifies the object on which it is invoked account.deposit(1000); Immutable class: has no mutator methods (e.g., String) String name = "John Q. Public"; String uppercased = name.toUpperCase(); // name is not changed It is safe to give out references to objects of immutable classes; no code can modify the object at an unexpected time

Self Check 8.6 Is the substring method of the String class an accessor or a mutator? Answer: It is an accessor – calling substring doesn't modify the string on which the method is invoked. In fact, all methods of the String class are accessors.

Self Check 8.7 Is the Rectangle class immutable? Answer: No – translate is a mutator.

Side Effects Side effect of a method: any externally observable data modification public void transfer(double amount, BankAccount other) { balance = balance - amount; other.balance = other.balance + amount; // Modifies explicit parameter } Updating explicit parameters can be surprising to programmers; it is best to avoid it if possible

Self Check 8.8 If a refers to a bank account, then the call a.deposit(100) modifies the bank account object. Is that a side effect? Answer: No – a side effect of a method is any change outside the implicit parameter.

Self Check 8.9 Consider the DataSet class of Chapter 6. Suppose we add a method void read(Scanner in) { while (in.hasNextDouble()) add(in.nextDouble()); } Does this method have a side effect? Answer: Yes – the method affects the state of the Scanner parameter.

Common Error: Trying to Modify Primitive Type Parameters void transfer(double amount, double otherBalance) { balance = balance - amount; otherBalance = otherBalance + amount; } This will not work! Scenario: double savingsBalance = 1000; harrysChecking.transfer(500, savingsBalance); System.out.println(savingsBalance); When savingsBalance is passed to transfer, its contents (1000) are copied into otherBalance---but they are not copied back In Java, a method can never modify parameters of any primitive type

Call by Value and Call by Reference Call by value: Method parameters are copied into the parameter variables when a method starts This is what Java does Call by reference: Methods can modify parameters Supported by other languages (e.g. C++) but not Java A method can change the state of an object through an object reference parameter, but cannot modify the reference itself

Call by Value and Call by Reference (cont.) public class BankAccount { public void transfer(double amount, BankAccount otherAccount) { balance = balance - amount; double newBalance = otherAccount.balance + amount; otherAccount = new BankAccount(newBalance); // This won't work! } }

Call by Value Example   harrysChecking.transfer(500, savingsAccount);

Corrected Version public class BankAccount { public void transfer(double amount, BankAccount otherAccount) { balance = balance - amount; double newBalance = otherAccount.balance + amount; otherAccount.balance = newBalance; // This will work! } }

Static Methods A static method belongs to a class: Is not invoked for a specific object of that class Is invoked by referring to the class name: e.g. Math.sin(0.4); Why write a method that does not operate on an object? Common reason: encapsulate some computation that involves only numbers. Numbers aren't objects, you can't invoke methods on them. E.g., x.sqrt() can never be legal in Java public class Financial { public static double percentOf(double p, double a) { return (p / 100) * a; } }

Static Methods (cont.) Call with class name not object name: double tax = Financial.percentOf(taxRate, total); main is static – it has to be because there are no objects created when the program starts running. It is the job of main to start the process of creating objects.

Self Check 8.12 Suppose Java had no static methods. Then all methods of the Math class would be instance methods. How would you compute the square root of x? Answer: Math m = new Math(); double y = m.sqrt(x);

Self Check 8.13 Harry turns in his homework assignment, a program that plays tic-tac-toe. His solution consists of a single class with many static methods. Why is this not an object-oriented solution? Answer: In an object-oriented solution, the main method would construct objects of classes Game, Player, and the like. Most methods would be instance methods that depend on the state of these objects.

Static Fields A static field belongs to the class, not to any object of the class. Also called class field Assume we wish to create BankAccounts, but we wish the account numbers to be assigned automatically by the constructor. BankAccount accountA = new BankAccount(); // acc. # 1001 BankAccount accountB = new BankAccount(); // acc. # 1002 public class BankAccount { . . . private double balance; private int accountNumber; private static int lastAssignedNumber = 1000; } If lastAssignedNumber was not static, each instance of BankAccount would have its own value of lastAssignedNumber

Static Fields (cont.) public BankAccount() { // Generates next account number to be assigned lastAssignedNumber++; // Updates the static field // Assigns field to account number of this account accountNumber = lastAssignedNumber; } Static fields have their uses, but they should be used with caution (static final fields are ok)

Three ways to initialize: Static Fields Three ways to initialize: Do nothing. Field is initialized with 0 (for numbers), false (for boolean values), or null (for objects) Use an explicit initializer, such as public class BankAccount { . . . private static int lastAssignedNumber = 1000; // Executed once, // when class is loaded Use a static initialization block Static fields should always be declared as private

Static Fields (cont.) Exception: Static constants, which may be either private or public public class BankAccount { . . . public static final double OVERDRAFT_FEE = 5; }

A Static Field and Instance Fields

Self Check 8.14 Name two static fields of the System class. Answer: System.in and System.out.

Self Check 8.15 Harry tells you that he has found a great way to avoid those pesky objects: Put all code into a single class and declare all methods and fields static. Then main can call the other static methods, and all of them can access the static fields. Will Harry's plan work? Is it a good idea? Answer: Yes, it works. Static methods can access static fields of the same class. But it is a terrible idea. As your programming tasks get more complex, you will want to use objects and classes to organize your programs.