Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 – Sections covered

Similar presentations


Presentation on theme: "Chapter 8 – Sections covered"— Presentation transcript:

1 Chapter 8 – Sections covered
8.1 – 8.9 Skip 8.10; ; 8.12; 8.13

2 Final exam Will be cumulative (more details soon)
It will be given on Thursday, December 18th from 4:00 to 5:50 pm in room 810 Silver.

3 Schedule for the rest of the semester
Nov 24 Strings Dec 2 terms and rules Dec 4 odds & ends; review Dec 9 review

4 Casting Objects It is always possible to convert a subclass to a superclass. For this reason, explicit casting can be omitted. For example, Circle myCircle = myCylinder is equivalent to Circle myCircle = (Circle)myCylinder; From Liang book

5 Casting from Superclass to Subclass
Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Cylinder myCylinder = (Cylinder)myCircle; From Liang book

6 The instanceof Operator
Use the instanceof operator to test whether an object is an instance of a class: Circle myCircle = new Circle(); if (myCircle instanceof Cylinder) { Cylinder myCylinder = (Cylinder)myCircle; ... } From Liang book

7 10.7 Case Study: Payroll System Using Polymorphism
Create a payroll program Use abstract methods and polymorphism Problem statement 4 types of employees, paid weekly Salaried (fixed salary, no matter the hours) Hourly (overtime [>40 hours] pays time and a half) Commission (paid percentage of sales) Base-plus-commission (base salary + percentage of sales) Boss wants to raise pay by 10%

8 10.9 Case Study: Payroll System Using Polymorphism
Superclass Employee Abstract method earnings (returns pay) abstract because need to know employee type Cannot calculate for generic employee Other classes extend Employee Employee SalariedEmployee HourlyEmployee CommissionEmployee BasePlusCommissionEmployee

9 Employee.java Line 4 Declares class Employee as abstract class.
// Fig : Employee.java // Employee abstract superclass. 3 public abstract class Employee { private String firstName; private String lastName; private String socialSecurityNumber; 8 // constructor public Employee( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } 16 // set first name public void setFirstName( String first ) { firstName = first; } 22 Declares class Employee as abstract class. Employee.java Line 4 Declares class Employee as abstract class.

10 Employee.java 23 // return first name 24 public String getFirstName()
{ return firstName; } 28 // set last name public void setLastName( String last ) { lastName = last; } 34 // return last name public String getLastName() { return lastName; } 40 // set social security number public void setSocialSecurityNumber( String number ) { socialSecurityNumber = number; // should validate } 46 Employee.java

11 Employee.java Line 61 Abstract method overridden by subclasses.
// return social security number public String getSocialSecurityNumber() { return socialSecurityNumber; } 52 // return String representation of Employee object public String toString() { return getFirstName() + " " + getLastName() + "\nsocial security number: " + getSocialSecurityNumber(); } 59 // abstract method overridden by subclasses public abstract double earnings(); 62 63 } // end abstract class Employee Employee.java Line 61 Abstract method overridden by subclasses. Abstract method overridden by subclasses

12 Use superclass constructor for basic fields.
// Fig : SalariedEmployee.java // SalariedEmployee class extends Employee. 3 public class SalariedEmployee extends Employee { private double weeklySalary; 6 // constructor public SalariedEmployee( String first, String last, String socialSecurityNumber, double salary ) { super( first, last, socialSecurityNumber ); setWeeklySalary( salary ); } 14 // set salaried employee's salary public void setWeeklySalary( double salary ) { weeklySalary = salary < 0.0 ? 0.0 : salary; } 20 // return salaried employee's salary public double getWeeklySalary() { return weeklySalary; } 26 SalariedEmployee.java Line 11 Use superclass constructor for basic fields. Use superclass constructor for basic fields.

13 Must implement abstract method earnings.
// calculate salaried employee's pay; // override abstract method earnings in Employee public double earnings() { return getWeeklySalary(); } 33 // return String representation of SalariedEmployee object public String toString() { return "\nsalaried employee: " + super.toString(); } 39 40 } // end class SalariedEmployee Must implement abstract method earnings. SalariedEmployee.java Lines Must implement abstract method earnings.

14 HourlyEmployee.java 1 // Fig. 10.14: HourlyEmployee.java
2 // HourlyEmployee class extends Employee. 3 4 public class HourlyEmployee extends Employee { private double wage; // wage per hour private double hours; // hours worked for week 7 // constructor public HourlyEmployee( String first, String last, String socialSecurityNumber, double hourlyWage, double hoursWorked ) { super( first, last, socialSecurityNumber ); setWage( hourlyWage ); setHours( hoursWorked ); } 16 // set hourly employee's wage public void setWage( double wageAmount ) { wage = wageAmount < 0.0 ? 0.0 : wageAmount; } 22 // return wage public double getWage() { return wage; } 28 HourlyEmployee.java

15 Must implement abstract method earnings.
// set hourly employee's hours worked public void setHours( double hoursWorked ) { hours = ( hoursWorked >= 0.0 && hoursWorked <= ) ? hoursWorked : 0.0; } 35 // return hours worked public double getHours() { return hours; } 41 // calculate hourly employee's pay; // override abstract method earnings in Employee public double earnings() { if ( hours <= 40 ) // no overtime return wage * hours; else return 40 * wage + ( hours - 40 ) * wage * 1.5; } 51 // return String representation of HourlyEmployee object public String toString() { return "\nhourly employee: " + super.toString(); } 57 58 } // end class HourlyEmployee HourlyEmployee.java Lines Must implement abstract method earnings. Must implement abstract method earnings.

16 CommissionEmployee.java 1 // Fig. 10.15: CommissionEmployee.java
// CommissionEmployee class extends Employee. 3 public class CommissionEmployee extends Employee { private double grossSales; // gross weekly sales private double commissionRate; // commission percentage 7 // constructor public CommissionEmployee( String first, String last, String socialSecurityNumber, double grossWeeklySales, double percent ) { super( first, last, socialSecurityNumber ); setGrossSales( grossWeeklySales ); setCommissionRate( percent ); } 17 // set commission employee's rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } 23 // return commission employee's rate public double getCommissionRate() { return commissionRate; } CommissionEmployee.java

17 Must implement abstract method earnings.
29 // set commission employee's weekly base salary public void setGrossSales( double sales ) { grossSales = sales < 0.0 ? 0.0 : sales; } 35 // return commission employee's gross sales amount public double getGrossSales() { return grossSales; } 41 // calculate commission employee's pay; // override abstract method earnings in Employee public double earnings() { return getCommissionRate() * getGrossSales(); } 48 // return String representation of CommissionEmployee object public String toString() { return "\ncommission employee: " + super.toString(); } 54 55 } // end class CommissionEmployee CommissionEmployee.java Lines Must implement abstract method earnings. Must implement abstract method earnings.

18 1 // Fig. 10.16: BasePlusCommissionEmployee.java
2 // BasePlusCommissionEmployee class extends CommissionEmployee. 3 4 public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary; // base salary per week 6 // constructor public BasePlusCommissionEmployee( String first, String last, String socialSecurityNumber, double grossSalesAmount, double rate, double baseSalaryAmount ) { super( first, last, socialSecurityNumber, grossSalesAmount, rate ); setBaseSalary( baseSalaryAmount ); } 15 // set base-salaried commission employee's base salary public void setBaseSalary( double salary ) { baseSalary = salary < 0.0 ? 0.0 : salary; } 21 // return base-salaried commission employee's base salary public double getBaseSalary() { return baseSalary; } 27 BasePlusCommissionEmployee.java

19 Override method earnings in CommissionEmployee
// calculate base-salaried commission employee's earnings; // override method earnings in CommissionEmployee public double earnings() { return getBaseSalary() + super.earnings(); } 34 // return String representation of BasePlusCommissionEmployee public String toString() { return "\nbase-salaried commission employee: " + super.getFirstName() + " " + super.getLastName() + "\nsocial security number: " + super.getSocialSecurityNumber(); } 42 43 } // end class BasePlusCommissionEmployee Override method earnings in CommissionEmployee BasePlusCommissionEmployee.java Lines Override method earnings in CommissionEmployee

20 PayrollSystemTest.java 1 // Fig. 10.17: PayrollSystemTest.java
// Employee hierarchy test program. import java.text.DecimalFormat; import javax.swing.JOptionPane; 5 public class PayrollSystemTest { 7 public static void main( String[] args ) { DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 11 // create Employee array Employee employees[] = new Employee[ 4 ]; 14 // initialize array with Employees employees[ 0 ] = new SalariedEmployee( "John", "Smith", " ", ); employees[ 1 ] = new CommissionEmployee( "Sue", "Jones", " ", 10000, .06 ); employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis", " ", 5000, .04, 300 ); employees[ 3 ] = new HourlyEmployee( "Karen", "Price", " ", 16.75, 40 ); 24 String output = ""; 26 PayrollSystemTest.java

21 Determine whether element is a BasePlusCommissionEmployee
// generically process each element in array employees for ( int i = 0; i < employees.length; i++ ) { output += employees[ i ].toString(); 30 // determine whether element is a BasePlusCommissionEmployee if ( employees[ i ] instanceof BasePlusCommissionEmployee ) { 33 // downcast Employee reference to // BasePlusCommissionEmployee reference BasePlusCommissionEmployee currentEmployee = ( BasePlusCommissionEmployee ) employees[ i ]; 38 double oldBaseSalary = currentEmployee.getBaseSalary(); output += "\nold base salary: $" + oldBaseSalary; 41 currentEmployee.setBaseSalary( 1.10 * oldBaseSalary ); output += "\nnew base salary with 10% increase is: $" + currentEmployee.getBaseSalary(); 45 } // end if 47 output += "\nearned $" + employees[ i ].earnings() + "\n"; 49 } // end for 51 PayrollSystemTest.java Line 32 Determine whether element is a BasePlusCommissionEmployee Line 37 Downcast Employee reference to BasePlusCommissionEmployee reference Determine whether element is a BasePlusCommissionEmployee Downcast Employee reference to BasePlusCommissionEmployee reference

22 Get type name of each object in employees array
for ( int j = 0; j < employees.length; j++ ) output += "\nEmployee " + j + " is a " + employees[ j ].getClass().getName(); 56 JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); 59 } // end main 61 62 } // end class PayrollSystemTest Get type name of each object in employees array PayrollSystemTest.java Lines Get type name of each object in employees array

23 10.8 Case Study: Creating and Using Interfaces
Use interface Shape Replace abstract class Shape Interface Declaration begins with interface keyword Classes implement an interface (and its methods) Contains public abstract methods Classes (that implement the interface) must implement these methods

24 Classes that implement Shape must implement these methods
// Fig : Shape.java // Shape interface declaration. 3 public interface Shape { public double getArea(); // calculate area public double getVolume(); // calculate volume public String getName(); // return shape name 8 } // end interface Shape Classes that implement Shape must implement these methods Shape.java Lines 5-7 Classes that implement Shape must implement these methods

25 Point.java Line 4 Point implements interface Shape
// Fig : Point.java // Point class declaration implements interface Shape. 3 public class Point extends Object implements Shape { private int x; // x part of coordinate pair private int y; // y part of coordinate pair 7 // no-argument constructor; x and y default to 0 public Point() { // implicit call to Object constructor occurs here } 13 // constructor public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here x = xValue; // no need for validation y = yValue; // no need for validation } 21 // set x in coordinate pair public void setX( int xValue ) { x = xValue; // no need for validation } 27 Point implements interface Shape Point.java Line 4 Point implements interface Shape

26 Point.java 28 // return x from coordinate pair 29 public int getX()
{ return x; } 33 // set y in coordinate pair public void setY( int yValue ) { y = yValue; // no need for validation } 39 // return y from coordinate pair public int getY() { return y; } 45 Point.java

27 Point.java Lines 47-59 Implement methods specified by interface Shape
// declare abstract method getArea public double getArea() { return 0.0; } 51 // declare abstract method getVolume public double getVolume() { return 0.0; } 57 // override abstract method getName to return "Point" public String getName() { return "Point"; } 63 // override toString to return String representation of Point public String toString() { return "[" + getX() + ", " + getY() + "]"; } 69 70 } // end class Point Implement methods specified by interface Shape Point.java Lines Implement methods specified by interface Shape

28 InterfaceTest.java Line 23 Create Shape array
// Fig : InterfaceTest.java // Test Point, Circle, Cylinder hierarchy with interface Shape. import java.text.DecimalFormat; import javax.swing.JOptionPane; 5 public class InterfaceTest { 7 public static void main( String args[] ) { // set floating-point number format DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 12 // create Point, Circle and Cylinder objects Point point = new Point( 7, 11 ); Circle circle = new Circle( 22, 8, 3.5 ); Cylinder cylinder = new Cylinder( 20, 30, 3.3, ); 17 // obtain name and string representation of each object String output = point.getName() + ": " + point + "\n" + circle.getName() + ": " + circle + "\n" + cylinder.getName() + ": " + cylinder + "\n"; 22 Shape arrayOfShapes[] = new Shape[ 3 ]; // create Shape array 24 InterfaceTest.java Line 23 Create Shape array Create Shape array

29 25 // aim arrayOfShapes[ 0 ] at subclass Point object
arrayOfShapes[ 0 ] = point; 27 // aim arrayOfShapes[ 1 ] at subclass Circle object arrayOfShapes[ 1 ] = circle; 30 // aim arrayOfShapes[ 2 ] at subclass Cylinder object arrayOfShapes[ 2 ] = cylinder; 33 // loop through arrayOfShapes to get name, string // representation, area and volume of every Shape in array for ( int i = 0; i < arrayOfShapes.length; i++ ) { output += "\n\n" + arrayOfShapes[ i ].getName() + ": " + arrayOfShapes[ i ].toString() + "\nArea = " + twoDigits.format( arrayOfShapes[ i ].getArea() ) + "\nVolume = " + twoDigits.format( arrayOfShapes[ i ].getVolume() ); } 43 JOptionPane.showMessageDialog( null, output ); // display output 45 System.exit( 0 ); 47 } // end main 49 50 } // end class InterfaceTest InterfaceTest.java Lines Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array. Loop through arrayOfShapes to get name, string representation, area and volume of every shape in array

30 InterfaceTest.java

31 10.8 Case Study: Creating and Using Interfaces (Cont.)
Implementing Multiple Interface Provide common-separated list of interface names after keyword implements Declaring Constants with Interfaces public interface Constants { public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; }

32 10.10 Type-Wrapper Classes for Primitive Types
Each primitive type has one Character, Byte, Integer, Boolean, etc. Enable to represent primitive as Object Primitive types can be processed polymorphically Declared as final Many methods are declared static


Download ppt "Chapter 8 – Sections covered"

Similar presentations


Ads by Google