Example: O-O Payroll Program (§11.4) Object-Oriented Design Behavior. Our program should read a sequence of employees from an input file, ( managers, secretaries,

Slides:



Advertisements
Similar presentations
Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
Advertisements

Lecture 15: I/O and Parsing
Inheritance and OOP Chapter 11. Chapter Contents Chapter Objectives 11.1 Introductory Example: A Trip to the Aviary 11.2 Inheritance and Polymorphism.
Written by: Dr. JJ Shepherd
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Programming With Java ICS 201 University Of Ha’il1 Chapter 8 Abstract Class.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Abstract Classes. Lecture Objectives To learn about abstract classes To understand how to inherit abstract classes To understand how to override abstract.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
March 2004Object Oriented Design1 Object-Oriented Design.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
CSC3170 Introduction to Database Systems
 Simple payroll application that polymorphically calculates the weekly pay of several different types of employees using each employee’s Earnings method.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
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,
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
CSCE 2013L: Lab 1 Overview  Java Basics The JVM Anatomy of a Java Program  Object-Oriented Programming Overview  Example: Payroll.java JDK Tools and.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
JAVA Object Oriented Programming. Objectives Be able to implement inheritance using extends, super, and abstract Be able to describe differences between.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Programming With Java ICS Chapter 8 Polymorphism.
CSC 142 Computer Science II Zhen Jiang West Chester University
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 14.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/14) Object Oriented Programming Joel Adams and Jeremy Frens Calvin.
Object-Oriented Programming. An object is anything that can be represented by data in a computer’s memory and manipulated by a computer program.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Inheritance and Design CSIS 3701: Advanced Object Oriented Programming.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
JAVA PROGRAMMING PART III. METHOD STATEMENT Form of method statement [ ] [static] ( [ ]) { } Example public static void main(String args[])
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
Inheritance ndex.html ndex.htmland “Java.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
OOP Basics Classes & Methods (c) IDMS/SQL News
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Polymorphism 2nd Lecture
Web Design & Development Lecture 5
Polymorphism 2nd Lecture
مظفر بگ محمدی دانشگاه ایلام
Exceptions.
Exceptions.
Classes and Methods 15-Aug-19.
Presentation transcript:

Example: O-O Payroll Program (§11.4) Object-Oriented Design Behavior. Our program should read a sequence of employees from an input file, ( managers, secretaries, programmers, and consultants). It should compute their pay and print a paycheck for each employee showing the employee’s name, ID, and pay. 1

2

OOD Analysis Kind of employee Common Attributes Managers, programmerssalary Create a SalariedEmployee class Make Manager and Programmer subclasses. Secretaries, consultants hourly wage, hours Create an HourlyEmployee class Make Secretary and Consultant subclasses. Salaried employee, hourly employees name, ID number, pay, etc. Create an Employee class Make SalariedEmployee and HourlyEmployee subclasses. 3

4 Object Payroll Generator Employee Paycheck Salaried Employee Hourly Employee ManagerProgrammerConsultantSecretary

5 OperationResponsibility of i. Read a sequence of employees PayrollGenerator from a file (open a stream to a file, read an Employee from a stream, Employee, subclasses close a stream to a file) ii. Compute an employee’s pay Employee iii. Construct a paycheck Paycheck iv. Access an employee’s name Employee v. Access an employee’s ID number Employee vi.Access an employee’s pay Employee, subclasses

6 Object Payroll Generator main() readFile() Employee String name() int id() double pay() void read(BufferedReader) Salaried Employee double salary() double pay() void read() Hourly Employee double rate() double hours() double pay() void read() Manager String division() void read() Programmer String project() void read() Secretary String worksFor() void read() String name() double amount() int id() PaycheckConsultant

7 Number of employees Employee #1 kind Employee #1 name Employee #1 id Employee #1 salary Employee #1 division Employee #2 kind Employee #2 name Employee #2 id Employee #2 wage Employee #2 hours Employee #2 works for... 7 Manager Grumpy Javadoc Secretary Bashful Grumpy... File Format

8 abstract class Employee extends Object { //--- Employee constructors //--- Accessor methods //--- String converter (for output) //--- File input --- void read(BufferedReader reader) { try { myName = reader.readLine(); myID = new Integer(reader.readLine()).intValue(); } catch (Exception error) { System.err.println("Employee:read(): " + error); System.exit(1); } //--- Abstract pay method --- abstract public double pay(); //--- Attribute variables --- private String myName; private int myID; } Because an employee’s pay is computed differently for salaried and hourly employees, we declare an abstract pay() method in class Employee so that pay() messages can be sent to an Employee handle.

9 class SalariedEmployee extends Employee { //--- Constructors //--- Accessor methods --- public double pay() { return salary(); } public double salary() { return mySalary; }... //--- String converter (for output) //--- File input //--- Attribute variables --- private double mySalary; } But only subclasses SalariedEmployee and HourlyEmployee will know how to compute their pay, and so we leave it to them to supply a definition for this method:

10 class HourlyEmployee extends Employee { public final static double OVERTIME_THRESHOLD = 40; public final static double OVERTIME_FACTOR = 1.5; //--- Constructors //--- Accessor methods //--- Pay for hourly employee --- public double pay() { if (myHours <= OVERTIME_THRESHOLD) return myHours * myHourlyRate; else return OVERTIME_THRESHOLD * myHourlyRate + (myHours - OVERTIME_THRESHOLD) * myHourlyRate * OVERTIME_FACTOR; }... //--- String converter (for output) //--- File input --- }... //--- Attribute variables --- private double myHourlyRate; private double myHours; } pay() is defined differently in SalariedEmployee and HourlyEmployee. Polymorphism selects the correct version.

11 class Manager extends SalariedEmployee { //--- Constructors //--- Accessor method --- public String division() { return myDivision; }... //--- String converter (for output) //--- File input --- //--- Attribute variable --- private String myDivision; } The Manager class is defined as a subclass of SalariedEmployee. Note that although pay() was an abstract method in the root class Employee, it was defined in SalariedEmployee, and it is this definition that is inherited by Manager.

12 class Programmer extends SalariedEmployee { //--- Constructors //--- Accessor method --- public String project() { return myProject; }... //--- File input //--- Attribute variable --- private String myProject; } Similarly, the Programmer class is defined as a subclass of SalariedEmployee : And Secretary and Consultant classes are defined as subclasses of HourlyEmployee and inherit it's methods, including the pay() method.

13 /** Paycheck.java provides a class to model paychecks. * New attribute variables store a name, check amount, * and ID number. * Methods: Constructors: to construct a Paycheck from Employee * accessors; to-string converter for output purposes; */ import java.text.*; // NumberFormat class Paycheck extends Object { //--- Paycheck constructor --- public Paycheck(Employee employee) { myName = employee.name(); myAmount = employee.pay(); myID = employee.id(); } The Paycheck class is designed to model paychecks:

14 //--- Accessor methods --- public String name() { return myName; } public double amount() { return myAmount; } public int id() { return myID; } //--- String converter (for output) --- public String toString() { NumberFormat cf = NumberFormat.getCurrencyInstance(); String formattedAmount = cf.format(myAmount); return myName + "\t\t" + formattedAmount + "\n" + myID; } //--- Attribute variables --- private String myName; private double myAmount; private int myID; } Note the use of the NumberFormat class method getCurrencyInstance() to create a number formatter for monetary values; it is then sent the format() message along with by the amount to be formatted to produce a String with the appropriate format.

15 class PayrollGenerator { public static void main(String [] args) { Employee [] employee = readFile(args[0]); for (int i = 0; i < employee.length; i++) { Paycheck check = new Paycheck(employee[i]); System.out.println(check + "\n"); } public static Employee [] readFile(String fileName) { BufferedReader empFile = null; int numberOfEmployees = 0; Employee [] result = null; try { empFile = new BufferedReader(new FileReader(fileName)); numberOfEmployees = new Integer(empFile.readLine()).intValue(); result = new Employee[numberOfEmployees]; int i = 0; Finally, there's the PayrollGenerator class that calculates wages and prepares paychecks:

16 String className = ""; for (;;) { String blankLine = empFile.readLine(); // eat blank line className = empFile.readLine(); if (className == null || className == "" // end of stream || i == result.length) // end of array break; result[i] = (Employee)Class.forName(className).newInstance(); result[i].read(empFile); i++; } empFile.close(); } catch (Exception e) { System.err.println(e); System.exit(1); } return result; } 1 2

17 Java has a class named Class that provides various operations for manipulating classes. Two useful ones are forName() and newInstance(). If String str is the name of a class, Class.forName(str) returns a Class object with name str ; and Class.forName(str).newInstance() returns an instance of the class with this name, created using the default constructor of that class. It returns that instance as an Object, and so it must be cast to an appropriate type, usually the nearest ancestor. For example, (Employee)Class.forName(className).newInstance() creates an object of type className.

18 employees.txt 7 Manager Grumpy Java Secretary Bashful Happy Programmer Happy Java IDE Consultant Doc Programmer Sneezy Java Debug Consultant Dopey Programmer Sleepy Java Threads java PayrollGenerator employees.txt Grumpy $ Bashful $ Happy $ Doc $ Sneezy $ Dopey $ Sleepy $

Example: Aviary Program (§11.1) Some special features of the bird hierarchy: The root class Bird along with subclasses WalkingBird and FlyingBird are abstract classes with abstract method getCall(). It uses the getClass( ) method from class Object. It has a random number generator used to select a random phrase by talking parrots and a random number of "Hoo"s by a snow owl: 19

import java.util.Random;... abstract class Bird extends Object {... //--- Random number generator --- /** Static random integer generator * Receive: int upperBound * Return: a random int from the range 0..upperBound-1 */ protected static int randomInt(int upperBound) { return myRandom.nextInt(upperBound); } //--- Attribute variables private static Random myRandom = new Random(); } 20

/** SnowOwl.java provides a subclass of Owl that models a * snow owl. It provides a constructor and a definition * of getCall(). */ class SnowOwl extends Owl { public SnowOwl() { super("white"); } public String getCall() { String call = ""; int randomNumber = randomInt(4) + 1; // 1..4 for (int count = 1; count <= randomNumber; count++) call += "Hoo"; return call + "!"; } 21