Object-Oriented Programming: Polymorphism

Size: px
Start display at page:

Download "Object-Oriented Programming: Polymorphism"

Transcription

1 10 One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them. John Ronald Reuel Tolkien General propositions do not decide concrete cases. Oliver Wendell Holmes A philosopher of imposing stature doesn t think in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is not known in the time when he lives. Alfred North Whitehead Why art thou cast down, O my soul? Psalms 42:5 Object-Oriented Programming: Polymorphism OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods to create abstract classes. How polymorphism makes systems extensible and maintainable. To determine an object s type at execution time. To declare and implement interfaces.

2 Chapter 10 Object-Oriented Programming: Polymorphism 3 Assignment Checklist Date: Section: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching YES NO Fill in the Blank YES NO Short Answer YES NO Programming Output YES NO Correct the Code YES NO Lab Exercises Exercise 1 Payroll System Modification YES NO Follow-Up Question and Activity 1 Exercise 2 Accounts Payable System Modification YES NO Follow-Up Question and Activity 1 Debugging YES NO Labs Provided by Instructor Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6, 7, 8 Programming Challenges 1, 2

3 Chapter 10 Object-Oriented Programming: Polymorphism 5 Prelab Activities Matching Date: Section: After reading Chapter 10 of Java How to Program: Sixth Edition, answer the given questions. The questions are intended to test and reinforce your understanding of key concepts. You may answer the questions before or during the lab. For each term in the left column, write the letter for the description from the right column that best matches the term. Term 1. abstract method 2. getclass method 3. implements keyword 4. type-wrapper classes 5. downcasting 6. concrete class 7. polymorphism 8. instanceof 9. final 10. getname method 11. abstract class 12. interface Description a) Can be used in place of an abstract class when there is no default implementation to inherit. b) Indicates that a method cannot be overridden or that a class cannot be a superclass. c) Class method which returns the name of the class associated with the Class object. d) An operator that returns true if its left operand (a variable of a reference type) has the is-a relationship with its right operand (a class or interface name). e) Uses superclass references to manipulate sets of subclass objects in a generic manner. f) Casting a superclass reference to a subclass reference. g) Cannot be instantiated; used primarily for inheritance. h) Indicates that a class will declare each method in an interface with the signature specified in the interface declaration. i) Must be overridden in a subclass; otherwise, the subclass must be declared abstract. j) Returns an object that can be used to determine information about the object s class. k) A class that can be used to create objects. l) Classes in the java.lang package that are used to create objects containing values of primitive types.

4 Chapter 10 Object-Oriented Programming: Polymorphism 7 Prelab Activities Fill in the Blank Fill in the Blank Date: Section: Fill in the blanks for each of the following statements: 13. With, it becomes possible to design and implement systems that are more extensible. 14. Although we cannot instantiate objects of abstract superclasses, we can declare of abstract superclass types. 15. It is a syntax error if a class with one or more abstract methods is not explicitly declared. 16. It is possible to assign a superclass reference to a subclass variable by the reference to the subclass type. 17. A(n) may contain a set of public abstract methods and/or public static final fields. 18. When a method is invoked through a superclass reference to a subclass object, Java executes the version of the method found in the. 19. The operator determines whether the type of the object to which its left operand refers has an isa relationship with the type specified as its right operand. 20. To use an interface, a class must specify that it the interface and must declare every method in the interface with the signatures specified in the interface declaration. 21. When a class implements an interface, it establishes an relationship with the interface type.

5 Chapter 10 Object-Oriented Programming: Polymorphism 9 Prelab Activities Short Answer Short Answer Date: Section: In the space provided, answer each of the given questions. Your answers should be as concise as possible; aim for two or three sentences. 22. Describe the concept of polymorphism. 23. Define what it means to declare a method final and what it means to declare a class final. 24. What happens when a class specifies that it implements an interface, but does not provide declarations of all the methods in the interface?

6 10 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Short Answer 25. Describe how to determine the class name of an object s class. 26. Distinguish between an abstract class and a concrete class.

7 Chapter 10 Object-Oriented Programming: Polymorphism 11 Prelab Activities Programming Output Programming Output Date: Section: For each of the given program segments, read the code and write the output in the space provided below each program. [ Note: Do not execute these programs on a computer.] Use the class definitions in Fig. L 10.1 Fig. L 10.3 when answering Programming Output Exercises // Employee.java 2 // Employee abstract superclass. 3 4 public abstract class Employee 5 { 6 private String firstname; 7 private String lastname; 8 private String socialsecuritynumber; 9 10 // three-argument constructor 11 public Employee( String first, String last, String ssn ) 12 { 13 firstname = first; 14 lastname = last; 15 socialsecuritynumber = ssn; 16 } // end three-argument Employee constructor // set first name 19 public void setfirstname( String first ) 20 { 21 firstname = first; 22 } // end method setfirstname // return first name 25 public String getfirstname() 26 { 27 return firstname; 28 } // end method getfirstname // set last name 31 public void setlastname( String last ) 32 { 33 lastname = last; 34 } // end method setlastname // return last name 37 public String getlastname() 38 { 39 return lastname; 40 } // end method getlastname 41 Fig. L 10.1 Employee abstract superclass. (Part 1 of 2.)

8 12 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Programming Output 42 // set social security number 43 public void setsocialsecuritynumber( String ssn ) 44 { 45 socialsecuritynumber = ssn; // should validate 46 } // end method setsocialsecuritynumber // return social security number 49 public String getsocialsecuritynumber() 50 { 51 return socialsecuritynumber; 52 } // end method getsocialsecuritynumber // return String representation of Employee object 55 public String tostring() 56 { 57 return String.format( "%s %s\nsocial security number: %s", 58 getfirstname(), getlastname(), getsocialsecuritynumber() ); 59 } // end method tostring // abstract method overridden by subclasses 62 public abstract double earnings(); // no implementation here 63 } // end abstract class Employee Fig. L 10.1 Employee abstract superclass. (Part 2 of 2.) 1 // SalariedEmployee.java 2 // SalariedEmployee class extends Employee. 3 4 public class SalariedEmployee extends Employee 5 { 6 private double weeklysalary; 7 8 // four-argument constructor 9 public SalariedEmployee( String first, String last, String ssn, 10 double salary ) 11 { 12 super ( first, last, ssn ); // pass to Employee constructor 13 setweeklysalary( salary ); // validate and store salary 14 } // end four-argument SalariedEmployee constructor // set salary 17 public void setweeklysalary( double salary ) 18 { 19 weeklysalary = salary < 0.0? 0.0 : salary; 20 } // end method setweeklysalary // return salary 23 public double getweeklysalary() 24 { 25 return weeklysalary; 26 } // end method getweeklysalary // calculate earnings; override abstract method earnings in Employee 29 public double earnings() 30 { Fig. L 10.2 SalariedEmployee class derived from Employee. (Part 1 of 2.)

9 Chapter 10 Object-Oriented Programming: Polymorphism 13 Prelab Activities Programming Output 31 return getweeklysalary(); 32 } // end method earnings // return String representation of SalariedEmployee object 35 public String tostring() 36 { 37 return String.format( "salaried employee: %s\n%s: $%,.2f", 38 super.tostring(), "weekly salary", getweeklysalary() ); 39 } // end method tostring 40 } // end class SalariedEmployee Fig. L 10.2 SalariedEmployee class derived from Employee. (Part 2 of 2.) 1 // CommissionEmployee.java 2 // CommissionEmployee class extends Employee. 3 4 public class CommissionEmployee extends Employee 5 { 6 private double grosssales; // gross weekly sales 7 private double commissionrate; // commission percentage 8 9 // five-argument constructor 10 public CommissionEmployee( String first, String last, String ssn, 11 double sales, double rate ) 12 { 13 super ( first, last, ssn ); 14 setgrosssales( sales ); 15 setcommissionrate( rate ); 16 } // end five-argument CommissionEmployee constructor // set commission rate 19 public void setcommissionrate( double rate ) 20 { 21 commissionrate = ( rate > 0.0 && rate < 1.0 )? rate : 0.0 ; 22 } // end method setcommissionrate // return commission rate 25 public double getcommissionrate() 26 { 27 return commissionrate; 28 } // end method getcommissionrate // set gross sales amount 31 public void setgrosssales( double sales ) 32 { 33 grosssales = ( sales < 0.0 )? 0.0 : sales; 34 } // end method setgrosssales // return gross sales amount 37 public double getgrosssales() 38 { 39 return grosssales; 40 } // end method getgrosssales 41 Fig. L 10.3 CommissionEmployee class derived from Employee. (Part 1 of 2.)

10 14 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Programming Output 42 // calculate earnings; override abstract method earnings in Employee 43 public double earnings() 44 { 45 return getcommissionrate() * getgrosssales(); 46 } // end method earnings // return String representation of CommissionEmployee object 49 public String tostring() 50 { 51 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", 52 "commission employee", super.tostring(), 53 "gross sales", getgrosssales(), 54 "commission rate", getcommissionrate() ); 55 } // end method tostring 56 } // end class CommissionEmployee Fig. L 10.3 CommissionEmployee class derived from Employee. (Part 2 of 2.) 27. What is output by the following code segment? Assume that the code appears in the main method of an application. 1 SalariedEmployee employee1 = 2 new SalariedEmployee( "June", "Bug", " ", ); 3 4 CommissionEmployee employee2 = 5 new CommissionEmployee( "Archie", "Tic", " ", , 0.10 ); 6 7 System.out.printf( "Employee 1:\n%s\n\n", employee1 ); 8 System.out.printf( "Employee 2:\n%s\n\n", employee2 ); Your answer: 28. What is output by the following code segment? Assume that the code appears in the main method of an application. 1 Employee firstemployee = 2 new SalariedEmployee( "June", "Bug", " ", ); 3 4 Employee secondemployee = 5 new CommissionEmployee( "Archie", "Tic", " ", , 0.10 ); 6 7 System.out.printf( "Employee 1:\n%s\n\n", firstemployee ); 8 System.out.printf( "Employee 2:\n%s\n\n", secondemployee );

11 Chapter 10 Object-Oriented Programming: Polymorphism 15 Prelab Activities Programming Output Your answer: 29. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise SalariedEmployee salaried = ( SalariedEmployee ) firstemployee; 2 System.out.printf( "salaried:\n%s\n", salaried ); Your answer: 30. What is output by the following code segment? Assume that the code follows the statements in Programming Output Exercise CommissionEmployee commission = ( CommissionEmployee ) firstemployee; 2 System.out.println( "commission:\n%s\n", commission ); Your answer:

12 Chapter 10 Object-Oriented Programming: Polymorphism 17 Prelab Activities Correct the Code Correct the Code Date: Section: Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a syntax error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write no error. [ Note: There may be more than one error in a program segment.] For questions assume the following definition of abstract class Employee. 1 // Employee abstract superclass. 2 3 public abstract class Employee 4 { 5 private String firstname; 6 private String lastname; 7 8 // three-argument constructor 9 public Employee( String first, String last ) 10 { 11 firstname = first; 12 lastname = last; 13 } // end three-argument Employee constructor // return first name 16 public String getfirstname() 17 { 18 return firstname; 19 } // end method getfirstname // return last name 22 public String getlastname() 23 { 24 return lastname; 25 } // end method getlastname // return String representation of Employee object 28 public String tostring() 29 { 30 return String.format( "%s %s", getfirstname(), getlastname() ); 31 } // end method tostring // abstract method overridden by subclasses 34 public abstract double earnings(); // no implementation here 35 } // end abstract class Employee

13 18 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Correct the Code 31. The following concrete class should inherit from abstract class Employee. A TipWorker is paid by the hour plus their tips for the week. 1 // TipWorker.java 2 public final class TipWorker extends Employee 3 { 4 private double wage; // wage per hour 5 private double hours; // hours worked for week 6 private double tips; // tips for the week 7 8 public TipWorker( String first, String last, 9 double wageperhour, double hoursworked, double tipsearned ) 10 { 11 super ( first, last ); // call superclass constructor 12 setwage ( wageperhour ); 13 sethours( hoursworked ); 14 settips( tipsearned ); 15 } // set the wage 18 public void setwage( double wageperhour ) 19 { 20 wage = ( wageperhour < 0? 0 : wageperhour ); 21 } // set the hours worked 24 public void sethours( double hoursworked ) 25 { 26 hours = ( hoursworked >= 0 && hoursworked < 168? hoursworked : 0 ); 27 } // set the tips 30 public void settips( double tipsearned ) 31 { 32 tips = ( tipsearned < 0? 0 : tipsearned ); 33 } 34 } // end class TipWorker Your answer:

14 Chapter 10 Object-Oriented Programming: Polymorphism 19 Prelab Activities Correct the Code 32. The following code should define method tostring of class TipWorker in Correct the Code Exercise // return a string representation of a TipWorker 2 public String tostring() 3 { 4 return String.format( 5 "Tip worker: %s\n%s: $%,.2f; %s: %.2f; %s: $%,.2f\n", tostring(), 6 "hourly wage", wage, "hours worked", hours, "tips earned", tips ); 7 } Your answer: 33. The following code should input information about five TipWorker s from the user and then print that information and all the TipWorker s calculated earnings. 1 // Test2.java 2 import java.util.scanner; 3 4 public class Test2 5 { 6 public static void main( String args[] ) 7 { 8 Employee employee[]; 9 Scanner input = new Scanner( System.in ); for ( int i = 0 ; i < employee.length; i++ ) 12 { 13 System.out.print( "Input first name: " ); 14 String firstname = input.nextline(); System.out.print( "Input last name: " ); 17 String lastname = input.nextline(); System.out.print( "Input hours worked: " ); 20 double hours = input.nextdouble(); System.out.print( "Input tips earned: " ); 23 double tips = input.nextdouble(); employee[ i ] = new Employee( firstname, lastname, 2.63, hours, tips ); System.out.printf( "%s %s earned $%.2f\n", employee[ i ].getfirstname(), 28 employee[ i ].getlastname(), employee[ i ].earnings() ); input.nextline(); // clear any remaining characters in the input stream 31 } // end for 32 } // end main 33 } // end class Test2

15 20 Object-Oriented Programming: Polymorphism Chapter 10 Prelab Activities Correct the Code Your answer:

16 Chapter 10 Object-Oriented Programming: Polymorphism 21 Lab Exercises Lab Exercise 1 Payroll System Modification Date: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 10.4 Fig. L 10.5) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at and Lab Objectives This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edition. In this lab, you will practice: Creating a new class and adding it to an existing class hierarchy. Using the updated class hierarchy in a polymorphic application. The follow-up question and activity also will give you practice: Understanding polymorphism. Description of the Problem (Payroll System Modification) Modify the payroll system of Figs to include an additional Employee subclass PieceWorker that represents an employee whose pay is based on the number of pieces of merchandise produced. Class PieceWorker should contain private instance variables wage (to store the employee s wage per piece) and pieces (to store the number of pieces produced). Provide a concrete implementation of method earnings in class PieceWorker that calculates the employee s earnings by multiplying the number of pieces produced by the wage per piece. Create an array of Employee variables to store references to objects of each concrete class in the new Employee hierarchy. For each Employee, display its string representation and earnings.

17 22 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 1 Payroll System Modification Sample Output Employees processed polymorphically: salaried employee: John Smith social security number: weekly salary: $ earned $ hourly employee: Karen Price social security number: hourly wage: $16.75; hours worked: earned $ commission employee: Sue Jones social security number: gross sales: $10,000.00; commission rate: 0.06 earned $ base-salaried commission employee: Bob Lewis social security number: gross sales: $5,000.00; commission rate: 0.04; base salary: $ earned $ piece worker: Rick Bridges social security number: wage per piece: $2.25; pieces produced: 400 earned $ Program Template 1 // Lab Exercise 1: PieceWorker.java 2 // PieceWorker class extends Employee. 3 4 public class PieceWorker extends Employee 5 { // five-argument constructor 10 public PieceWorker( String first, String last, String ssn, 11 double wageperpiece, int piecesproduced ) 12 { 13 /* write code to initialize a PieceWorker */ 14 } // end five-argument PieceWorker constructor // set wage // return wage // set pieces produced /* declare instance variable wage */ /* declare instance variable pieces */ /* write a set method that validates and sets the PieceWorker's wage */ /* write a get method that returns the PieceWorker's wage */ /* write a set method that validates and sets the number of pieces produced */ Fig. L 10.4 PieceWorker.java. (Part 1 of 2.)

18 Chapter 10 Object-Oriented Programming: Polymorphism 23 Lab Exercises Lab Exercise 1 Payroll System Modification 25 // return pieces produced 26 /* write a get method that returns the number of pieces produced */ // calculate earnings; override abstract method earnings in Employee 29 public double earnings() 30 { 31 /* write code to return the earnings for a PieceWorker */ 32 } // end method earnings // return String representation of PieceWorker object 35 public String tostring() 36 { 37 /* write code to return a string representation of a PieceWorker */ 38 } // end method tostring 39 } // end class PieceWorker Fig. L 10.4 PieceWorker.java. (Part 2 of 2.) 1 // Lab Exercise 1: PayrollSystemTest.java 2 // Employee hierarchy test program. 3 4 public class PayrollSystemTest 5 { 6 public static void main( String args[] ) 7 { 8 // create five-element Employee array 9 Employee employees[] = new Employee[ 5 ]; // initialize array with Employees 12 employees[ 0 ] = new SalariedEmployee( 13 "John", "Smith", " ", ); 14 employees[ 1 ] = new HourlyEmployee( 15 "Karen", "Price", " ", 16.75, 40 ); 16 employees[ 2 ] = new CommissionEmployee( 17 "Sue", "Jones", " ", 10000,.06 ); 18 employees[ 3 ] = new BasePlusCommissionEmployee( 19 "Bob", "Lewis", " ", 5000,.04, 300 ); 20 /* create a PieceWoker object and assign it to employees[ 4 ] */ System.out.println( "Employees processed polymorphically:\n" ); // generically process each element in array employees 25 for ( Employee currentemployee : employees ) 26 { 27 System.out.println( currentemployee ); // invokes tostring 28 System.out.printf( 29 "earned $%,.2f\n\n", currentemployee.earnings() ); 30 } // end for 31 } // end main 32 } // end class PayrollSystemTest Fig. L 10.5 PayrollSystemTest.java Problem-Solving Tips 1. The PieceWorker constructor should call the superclass Employee constructor to initialize the employee s name.

19 24 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 1 Payroll System Modification 2. The number of pieces produced should be greater than or equal to 0. Place this logic in the set method for the pieces variable. 3. The wage should be greater than or equal to 0. Place this logic in the set method for the wage variable. 4. The main method must explicitly create a new PieceWorker object and assign it to an element of the employees array. 5. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Question and Activity 1. Explain the line of code in your PayrollSystemTest s main method that calls method earnings. Why can that line invoke method earnings on every element of the employees array?

20 Chapter 10 Object-Oriented Programming: Polymorphism 25 Lab Exercises Lab Exercise 2 Accounts Payable System Modification Lab Exercise 2 Accounts Payable System Modification Date: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of the Problem 3. Sample Output 4. Program Template (Fig. L 10.6 Fig. L 10.9) 5. Problem-Solving Tips 6. Follow-Up Question and Activity The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up question. The source code for the template is available at and Lab Objectives This lab was designed to reinforce programming concepts from Chapter 10 of Java How to Program: Sixth Edition. In this lab you will practice: Provide additional polymorphic processing capabilities to an inheritance hierarchy by implementing an interface. Using the instanceof operator to determine whether a variable refers to an object that has an is-a relationship with a particular class. The follow-up question and activity will also give you practice: Comparing interface s and abstract classes. Description of the Problem (Accounts Payable System Modification) In this exercise, we modify the accounts payable application of Figs to include the complete functionality of the payroll application. The application should still process two Invoice objects, but now should process one object of each of the four Employee subclasses (Figs ). If the object currently being processed is a BasePlusCommissionEmployee, the application should increase the BasePlusCommissionEmployee s base salary by 10%. Finally, the application should output the payment amount for each object. Complete the following steps to create the new application: a) Modify classes HourlyEmployee and CommissionEmployee to place them in the Payable hierarchy as subclasses of the version of Employee that implements Payable (Fig ). [ Hint: Change the name of method earnings to getpaymentamount in each subclass so that the class satisfies its inherited contract with interface Payable.] b) Modify class BasePlusCommissionEmployee such that it extends the version of class CommissionEmployee created in Part a.

21 26 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 2 Accounts Payable System Modification c) Modify PayableInterfaceTest to polymorphically process two Invoice s, one SalariedEmployee, one HourlyEmployee, one CommissionEmployee and one BasePlusCommissionEmployee. First output a string representation of each Payable object. Next, if an object is a BasePlusCommissionEmployee, increase its base salary by 10%. Finally, output the payment amount for each Payable object. Sample Output Invoices and Employees processed polymorphically: invoice: part number: (seat) quantity: 2 price per item: $ payment due: $ invoice: part number: (tire) quantity: 4 price per item: $79.95 payment due: $ salaried employee: John Smith social security number: weekly salary: $ payment due: $ hourly employee: Karen Price social security number: hourly wage: $16.75; hours worked: payment due: $ commission employee: Sue Jones social security number: gross sales: $10,000.00; commission rate: 0.06 payment due: $ base-salaried commission employee: Bob Lewis social security number: gross sales: $5,000.00; commission rate: 0.04; base salary: $ new base salary with 10% increase is: $ payment due: $ Program Template 1 // Lab Exercise 2: HourlyEmployee.java 2 // HourlyEmployee class extends Employee, which implements Payable. 3 4 public class HourlyEmployee extends Employee 5 { 6 private double wage; // wage per hour 7 private double hours; // hours worked for week 8 Fig. L 10.6 HourlyEmployee.java. (Part 1 of 2.)

22 Chapter 10 Object-Oriented Programming: Polymorphism 27 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 9 // five-argument constructor 10 public HourlyEmployee( String first, String last, String ssn, 11 double hourlywage, double hoursworked ) 12 { 13 super ( first, last, ssn ); 14 setwage( hourlywage ); // validate and store hourly wage 15 sethours( hoursworked ); // validate and store hours worked 16 } // end five-argument HourlyEmployee constructor // set wage 19 public void setwage( double hourlywage ) 20 { 21 wage = ( hourlywage < 0.0 )? 0.0 : hourlywage; 22 } // end method setwage // return wage 25 public double getwage() 26 { 27 return wage; 28 } // end method getwage // set hours worked 31 public void sethours( double hoursworked ) 32 { 33 hours = ( ( hoursworked >= 0.0 ) && ( hoursworked <= ) )? 34 hoursworked : 0.0; 35 } // end method sethours // return hours worked 38 public double gethours() 39 { 40 return hours; 41 } // end method gethours // calculate earnings; implement interface Payable method not 44 // implemented by superclass Employee /* write a method header to satisfy the Payable interface */ { 47 if ( gethours() <= 40 ) // no overtime 48 return getwage() * gethours(); 49 else 50 return 40 * getwage() + ( gethours() - 40 ) * getwage() * 1.5; 51 } // end method getpaymentamount // return String representation of HourlyEmployee object 54 public String tostring() 55 { 56 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", 57 super.tostring(), "hourly wage", getwage(), 58 "hours worked", gethours() ); 59 } // end method tostring 60 } // end class HourlyEmployee Fig. L 10.6 HourlyEmployee.java. (Part 2 of 2.)

23 28 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 1 // Lab Exercise 2: CommissionEmployee.java 2 // CommissionEmployee class extends Employee, which implements Payable. 3 4 public class CommissionEmployee extends Employee 5 { 6 private double grosssales; // gross weekly sales 7 private double commissionrate; // commission percentage 8 9 // five-argument constructor 10 public CommissionEmployee( String first, String last, String ssn, 11 double sales, double rate ) 12 { 13 super ( first, last, ssn ); 14 setgrosssales( sales ); 15 setcommissionrate( rate ); 16 } // end five-argument CommissionEmployee constructor // set commission rate 19 public void setcommissionrate( double rate ) 20 { 21 commissionrate = ( rate > 0.0 && rate < 1.0 )? rate : 0.0 ; 22 } // end method setcommissionrate // return commission rate 25 public double getcommissionrate() 26 { 27 return commissionrate; 28 } // end method getcommissionrate // set gross sales amount 31 public void setgrosssales( double sales ) 32 { 33 grosssales = ( sales < 0.0 )? 0.0 : sales; 34 } // end method setgrosssales // return gross sales amount 37 public double getgrosssales() 38 { 39 return grosssales; 40 } // end method getgrosssales // calculate earnings; implement interface Payable method not 43 // implemented by superclass Employee /* write a method header to satisfy the Payable interface */ { 46 return getcommissionrate() * getgrosssales(); 47 } // end method getpaymentamount // return String representation of CommissionEmployee object 50 public String tostring() 51 { 52 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", 53 "commission employee", super.tostring(), 54 "gross sales", getgrosssales(), 55 "commission rate", getcommissionrate() ); 56 } // end method tostring 57 } // end class CommissionEmployee Fig. L 10.7 CommissionEmployee.java.

24 Chapter 10 Object-Oriented Programming: Polymorphism 29 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 1 // Lab Exercise 2: BasePlusCommissionEmployee.java 2 // BasePlusCommissionEmployee class extends CommissionEmployee. 3 4 public class BasePlusCommissionEmployee extends CommissionEmployee 5 { 6 private double basesalary; // base salary per week 7 8 // six-argument constructor 9 public BasePlusCommissionEmployee( String first, String last, 10 String ssn, double sales, double rate, double salary ) 11 { 12 super ( first, last, ssn, sales, rate ); 13 setbasesalary( salary ); // validate and store base salary 14 } // end six-argument BasePlusCommissionEmployee constructor // set base salary 17 public void setbasesalary( double salary ) 18 { 19 basesalary = ( salary < 0.0 )? 0.0 : salary; // non-negative 20 } // end method setbasesalary // return base salary 23 public double getbasesalary() 24 { 25 return basesalary; 26 } // end method getbasesalary // calculate earnings; override CommissionEmployee implementation of 29 // interface Payable method { 32 /* write a method header to satisfy the Payable interface */ /* calculate and return the BasePlusCommissionEmployee's earnings */ 33 } // end method getpaymentamount // return String representation of BasePlusCommissionEmployee object 36 public String tostring() 37 { 38 return String.format( "%s %s; %s: $%,.2f", 39 "base-salaried", super.tostring(), 40 "base salary", getbasesalary() ); 41 } // end method tostring 42 } // end class BasePlusCommissionEmployee Fig. L 10.8 BasePlusCommissionEmployee.java. 1 // Lab Exercise 2: PayableInterfaceTest.java 2 // Tests interface Payable. 3 4 public class PayableInterfaceTest 5 { 6 public static void main( String args[] ) 7 { 8 // create six-element Payable array 9 Payable payableobjects[] = new Payable[ 6 ]; 10 Fig. L 10.9 PayableInterfaceTest.java. (Part 1 of 2.)

25 30 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Lab Exercise 2 Accounts Payable System Modification 11 // populate array with objects that implement Payable 12 payableobjects[ 0 ] = new Invoice( "01234", "seat", 2, ); 13 payableobjects[ 1 ] = new Invoice( "56789", "tire", 4, ); 14 payableobjects[ 2 ] = 15 new SalariedEmployee( "John", "Smith", " ", ); 16 payableobjects[ 3 ] = /* create an HourlyEmployee object */ payableobjects[ 4 ] = 19 /* create a CommissionEmployee object */ 20 payableobjects[ 5 ] = 21 /* create a BasePlusCommissionEmployee object */ System.out.println( 24 "Invoices and Employees processed polymorphically:\n" ); // generically process each element in array payableobjects 27 for ( Payable currentpayable : payableobjects ) 28 { 29 // output currentpayable and its appropriate payment amount 30 System.out.printf( "%s \n", currentpayable.tostring() ); { Problem-Solving Tips /* write code to determine whether currentpayable is a BasePlusCommissionEmployee object */ /* write code to give a raise */ /* write code to ouput results of the raise */ 37 } // end if System.out.printf( "%s: $%,.2f\n\n", 40 "payment due", currentpayable.getpaymentamount() ); 41 } // end for 42 } // end main 43 } // end class PayableInterfaceTest Fig. L 10.9 PayableInterfaceTest.java. (Part 2 of 2.) 1. Every class that implements interface Payable must declare a method called getpaymentamount. 2. Class BasePlusCommissionEmployee must use its superclass s getpaymentamount method along with its own base salary to calculate its total earnings. 3. Use the instanceof operator in PayableInterfaceTest to determine whether each object is a Base- PlusCommissionEmployee object. 4. If you have any questions as you proceed, ask your lab instructor for assistance. Follow-Up Question and Activity 1. Discuss the benefits and disadvantages of extending an abstract class vs. implementing an interface.

26 Chapter 10 Object-Oriented Programming: Polymorphism 31 Lab Exercises Debugging Debugging Date: Section: The program in this section does not compile. Fix all the syntax errors so that the program will compile successfully. Once the program compiles, execute the program, and compare the output with the sample output; then eliminate any logic errors that may exist. The sample output demonstrates what the program s output should be once the program s code is corrected. The source code is available at and at deitel. Sample Output Point: [7, 11] Circle: Center = [22, 8]; Radius = Cylinder: Center = [10, 10]; Radius = ; Height = Point: [7, 11] Area = 0.00 Volume = 0.00 Circle: Center = [22, 8]; Radius = Area = Volume = 0.00 Cylinder: Center = [10, 10]; Radius = ; Height = Area = Volume = Broken Code 1 // Shape.java 2 // Definition of interface Shape 3 4 public interface Shape 5 { 6 public abstract String getname(); // return shape name 7 } // end interface Shape 1 // Point.java 2 // Definition of class Point 3 4 public class Point implements Shape 5 { 6 protected int x, y; // coordinates of the Point 7 8 // no-argument constructor 9 public Point() 10 { 11 setpoint( 0, 0 ); 12 }

27 32 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging // constructor 15 public Point( int xcoordinate, int ycoordinate ) 16 { 17 setpoint( xcoordinate, ycoordinate ); 18 } // Set x and y coordinates of Point 21 public void setpoint( int xcoordinate, int ycoordinate ) 22 { 23 x = xcoordinate; 24 y = ycoordinate; 25 } // get x coordinate 28 public int getx() 29 { 30 return x; 31 } // get y coordinate 34 public int gety() 35 { 36 return y; 37 } // convert point into String representation 40 public String tostring() 41 { 42 return String.format( "[%d, %d]", x, y ); 43 } // calculate area 46 public double area() 47 { 48 return 0.0 ; 49 } // calculate volume 52 public double volume() 53 { 54 return 0.0 ; 55 } // return shape name 58 public String getname() 59 { 60 return "Point"; 61 } 62 } // end class Point 1 // Circle.java 2 // Definition of class Circle 3 4 public class Circle extends Point 5 { 6 protected double radius;

28 Chapter 10 Object-Oriented Programming: Polymorphism 33 Lab Exercises Debugging 7 8 // no-argument constructor 9 public Circle() 10 { 11 // implicit call to superclass constructor here 12 setradius( 0 ); 13 } // constructor 16 public Circle( double circleradius, int xcoordinate, int ycoordinate ) 17 { 18 super ( xcoordinate, ycoordinate ); // call superclass constructor setradius( circleradius ); 21 } // set radius of Circle 24 public void setradius( double circleradius ) 25 { 26 radius = ( circleradius >= 0? circleradius : 0 ); 27 } // get radius of Circle 30 public double getradius() 31 { 32 return radius; 33 } // calculate area of Circle 36 public double area() 37 { 38 return Math.PI * radius * radius; 39 } // convert Circle to a String represention 42 public String tostring() 43 { 44 return String.format( "Center = %s; Radius = %f", 45 super.tostring(), radius ); 46 } // return shape name 49 public String getname() 50 { 51 return "Circle"; 52 } 53 } // end class Circle 1 // Cylinder.java 2 // Definition of class Cylinder. 3 4 public class Cylinder extends Circle 5 { 6 protected double height; // height of Cylinder 7

29 34 Object-Oriented Programming: Polymorphism Chapter 10 Lab Exercises Debugging 8 // no-argument constructor 9 public Cylinder() 10 { 11 // implicit call to superclass constructor here 12 setheight( 0 ); 13 } // constructor 16 public Cylinder( double cylinderheight, double cylinderradius, 17 int xcoordinate, int ycoordinate ) 18 { 19 // call superclass constructor 20 super ( cylinderradius, xcoordinate, ycoordinate ); setheight( cylinderheight ); 23 } // set height of Cylinder 26 public void setheight( double cylinderheight ) 27 { 28 height = ( cylinderheight >= 0? cylinderheight : 0 ); 29 } // get height of Cylinder 32 public double getheight() 33 { 34 return height; 35 } // calculate area of Cylinder (i.e., surface area) 38 public double area() 39 { 40 return 2 * super.area() + 2 * Math.PI * radius * height; 41 } // calculate volume of Cylinder 44 public double volume() 45 { 46 return super.area() * height; 47 } // convert Cylinder to a String representation 50 public String tostring() 51 { 52 return String.format( "%s; Height = %f", 53 super.tostring(), height ); 54 } // return shape name 57 public String getname() 58 { 59 return "Cylinder"; 60 } 61 } // end class Cylinder

30 Chapter 10 Object-Oriented Programming: Polymorphism 35 Lab Exercises Debugging 1 // Test.java 2 // Test Point, Circle, Cylinder hierarchy with interface Shape. 3 4 public class Test 5 { 6 // test Shape hierarchy 7 public static void main( String args[] ) 8 { 9 // create shapes 10 Point point = new Point( 7, 11 ); 11 Circle circle = new Circle( 3.5, 22, 8 ); 12 Cylinder cylinder = new Cylinder( 10, 3.3, 10, 10 ); Cylinder arrayofshapes[] = new Cylinder[ 3 ]; // create Shape array // aim arrayofshapes[ 0 ] at subclass Point object 17 arrayofshapes[ 0 ] = ( Cylinder ) point; // aim arrayofshapes[ 1 ] at subclass Circle object 20 arrayofshapes[ 1 ] = ( Cylinder ) circle; // aim arrayofshapes[ 2 ] at subclass Cylinder object 23 arrayofshapes[ 2 ] = ( Cylinder ) cylinder; // get name and String representation of each shape 26 System.out.printf( "%s: %s\n%s: %s\n%s: %s\n", point.getname(), 27 point, circle.getname(), circle, cylinder.getname(), cylinder ); // get name, area and volume of each shape in arrayofshapes 30 for ( Shape shape : arrayofshapes ) 31 { 32 System.out.printf( "\n\n%s: %s\narea = %.2f\nVolume = %.2f\n", 33 shape.getname(), shape, shape.area(), shape.volume() ); 34 } // end for 35 } // end main 36 } // end class Test

31 Chapter 10 Object-Oriented Programming: Polymorphism 37 Postlab Activities Coding Exercises Date: Section: These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program segment that performs the specified action. 1. Write an empty class declaration for an abstract class called Shape. 2. In the class from Coding Exercise 1, create a protected instance variable shapename of type String, and write an accessor method getname for obtaining its value. 3. In the class of Coding Exercise 2, define an abstract method getarea that returns a double representation of a specific shape s area. Subclasses of this class must implement getarea to calculate a specific shape s area.

32 38 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Coding Exercises 4. Define a class Square that inherits from class Shape from Coding Exercise 3; it should contain an instance variable side, which represents the length of a side of the square. Provide a constructor that takes one argument representing the side of the square and sets the side variable. Ensure that the side is greater than or equal to 0. The constructor should set the inherited shapename variable to the string "Square". 5. The Square class from Coding Exercise 4 should implement the getarea method of its abstract superclass; this implementation should compute the area of the square and return the result. 6. Define a class Rectangle that inherits from class Shape of Coding Exercise 3. The new class should contain instance variables length and width. Provide a constructor that takes two arguments representing the length and width of the rectangle, sets the two variables and sets the inherited shapename variable to the string "Rectangle". Ensure that the length and width are both greater than or equal to 0.

33 Chapter 10 Object-Oriented Programming: Polymorphism 39 Postlab Activities Coding Exercises 7. The Rectangle class from Coding Exercise 6 should also implement the getarea method of its abstract superclass; this implementation should compute the area of the rectangle and return the result. 8. Write an application that tests the Square and Rectangle classes from Coding Exercises 5 and 7, respectively. Create an array of type Shape that holds an instance of Square and an instance of Rectangle. The program should polymorphically compute and display the areas of both objects. Allow a user to enter the values for the side of the square and the length and width of the rectangle.

34 Chapter 10 Object-Oriented Programming: Polymorphism 41 Postlab Activities Programming Challenges Programming Challenges Date: Section: The Programming Challenges are more involved than the Coding Exercises and may require a significant amount of time to complete. Write a Java program for each of the problems in this section. The answers to these problems are available at and Pseudocode, hints or sample outputs are provided for each problem to aid you in your programming. 1. (Payroll System Modification) Modify the payroll system of Figs to include private instance variable birthdate in class Employee. Use class Date of Fig. 8.7 to represent an employee s birthday. Add get methods to class Date and replace method todatestring with method tostring. Assume that payroll is processed once per month. Create an array of Employee variables to store references to the various employee objects. In a loop, calculate the payroll for each Employee (polymorphically), and add a $ bonus to the person s payroll amount if the current month is the month in which the Employee s birthday occurs. Hint: Your output should appear as follows: Date object constructor for date 6/15/1944 Date object constructor for date 12/29/1960 Date object constructor for date 9/8/1954 Date object constructor for date 3/2/1965 Employees processed individually: salaried employee: John Smith social security number: birth date: 6/15/1944 weekly salary: $ earned: $ hourly employee: Karen Price social security number: birth date: 12/29/1960 hourly wage: $16.75; hours worked: earned: $ commission employee: Sue Jones social security number: birth date: 9/8/1954 gross sales: $10,000.00; commission rate: 0.06 earned: $ base-salaried commission employee: Bob Lewis social security number: birth date: 3/2/1965 gross sales: $5,000.00; commission rate: 0.04; base salary: $ earned: $ Enter the current month (1-12): 3 (continued next page...)

35 42 Object-Oriented Programming: Polymorphism Chapter 10 Postlab Activities Programming Challenges Employees processed polymorphically: salaried employee: John Smith social security number: birth date: 6/15/1944 weekly salary: $ earned $ hourly employee: Karen Price social security number: birth date: 12/29/1960 hourly wage: $16.75; hours worked: earned $ commission employee: Sue Jones social security number: birth date: 9/8/1954 gross sales: $10,000.00; commission rate: 0.06 earned $ base-salaried commission employee: Bob Lewis social security number: birth date: 3/2/1965 gross sales: $5,000.00; commission rate: 0.04; base salary: $ new base salary with 10% increase is: $ earned $ plus $ birthday bonus Employee 0 is a SalariedEmployee Employee 1 is a HourlyEmployee Employee 2 is a CommissionEmployee Employee 3 is a BasePlusCommissionEmployee 2. (Shape Hierarchy) Implement the Shape hierarchy shown in Fig Each TwoDimensionalShape should contain method getarea to calculate the area of the two-dimensional shape. Each ThreeDimensionalShape should have methods getarea and getvolume to calculate the surface area and volume, respectively, of the three-dimensional shape. Create a program that uses an array of Shape references to objects of each concrete class in the hierarchy. The program should print a text description of the object to which each array element refers. Also, in the loop that processes all the shapes in the array, determine whether each shape is a Two- DimensionalShape or a ThreeDimensionalShape. If a shape is a TwoDimensionalShape, display its area. If a shape is a ThreeDimensionalShape, display its area and volume. Hint: Your output should appear as follows: Circle: [22, 88] radius: 4 Circle's area is 50 Square: [71, 96] side: 10 Square's area is 100 Sphere: [8, 89] radius: 2 Sphere's area is 50 Sphere's volume is 33 Cube: [79, 61] side: 8 Cube's area is 384 Cube's volume is 512

Object-Oriented Programming: Polymorphism Pearson Education, Inc. All rights reserved.

Object-Oriented Programming: Polymorphism Pearson Education, Inc. All rights reserved. 1 10 Object-Oriented Programming: Polymorphism 2 A Motivating Example Employee as an abstract superclass. Lots of different types of employees (well, 4). Executing the same code on all different types

More information

final Methods and Classes

final Methods and Classes 1 2 OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods

More information

Object-Oriented Programming: Polymorphism

Object-Oriented Programming: Polymorphism Object-Oriented Programming: Polymorphism By Harvey M. Deitel and Paul J. Deitel Jun 1, 2009 Sample Chapter is provided courtesy of Prentice Hall 10.1 Introduction We now continue our study of object-oriented

More information

Polymorphism (Deitel chapter 10) (Old versions: chapter 9)

Polymorphism (Deitel chapter 10) (Old versions: chapter 9) Polymorphism (Deitel chapter 10) (Old versions: chapter 9) 1 2 Plan Introduction Relationships Among Objects in an Inheritance Hierarchy Polymorphism Examples Abstract Classes and Methods Example: Inheriting

More information

WEEK 13 EXAMPLES: POLYMORPHISM

WEEK 13 EXAMPLES: POLYMORPHISM WEEK 13 EXAMPLES: POLYMORPHISM CASE STUDY: PAYROLL SYSTEM USING POLYMORPHISM Use the principles of inheritance, abstract class, abstract method, and polymorphism to design a payroll project for a car lot.

More information

Object Oriented Programming with C++ (24)

Object Oriented Programming with C++ (24) Object Oriented Programming with C++ (24) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Polymorphism (II) Chapter 13 Outline Review

More information

Inheritance Introduction. 9.1 Introduction 361

Inheritance Introduction. 9.1 Introduction 361 www.thestudycampus.com Inheritance 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship Between Superclasses and Subclasses 9.4.1 Creating and Using a CommissionEmployee

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Polymorphism Lecture 8 September 28/29, 2004 Introduction 2 Polymorphism Program in the general Derived-class object can be treated as base-class object is -a

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.

More information

Polymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

Polymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S. Chapter 4 Polymorphm CSC 113 King Saud University College Computer and Information Sciences Department Computer Science Objectives After you have read and studied th chapter, you should be able to Write

More information

BBM 102 Introduction to Programming II Spring Inheritance

BBM 102 Introduction to Programming II Spring Inheritance BBM 102 Introduction to Programming II Spring 2018 Inheritance 1 Today Inheritance Notion of subclasses and superclasses protected members UML Class Diagrams for inheritance 2 Inheritance A form of software

More information

Cpt S 122 Data Structures. Inheritance

Cpt S 122 Data Structures. Inheritance Cpt S 122 Data Structures Inheritance Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Base Classes & Derived Classes Relationship between

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Inheritance A form of software reuse in which a new class is created by absorbing an existing class s members and enriching them with

More information

C++ Polymorphism. Systems Programming

C++ Polymorphism. Systems Programming C++ Polymorphism Systems Programming C++ Polymorphism Polymorphism Examples Relationships Among Objects in an Inheritance Hierarchy Invoking Base-Class Functions from Derived-Class Objects Aiming Derived-Class

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

Object- Oriented Programming: Inheritance

Object- Oriented Programming: Inheritance 9 Say not you know another entirely, till you have divided an inheritance with him. Johann Kasper Lavater This method is to define as the number of a class the class of all classes similar to the given

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED - Polymorphism - Virtual Functions - Abstract Classes - Virtual

More information

Chapter 9 - Object-Oriented Programming: Polymorphism

Chapter 9 - Object-Oriented Programming: Polymorphism Chapter 9 - Object-Oriented Programming: Polymorphism Polymorphism Program in the general Introduction Treat objects in same class hierarchy as if all superclass Abstract class Common functionality Makes

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(a): Abstract Classes Lecture Contents 2 Abstract base classes Concrete classes Dr. Amal Khalifa, 2014 Abstract Classes and Methods

More information

Java How to Program, 8/e

Java How to Program, 8/e Java How to Program, 8/e Polymorphism Enables you to program in the general rather than program in the specific. Polymorphism enables you to write programs that process objects that share the same superclass

More information

Computer Programming Inheritance 10 th Lecture

Computer Programming Inheritance 10 th Lecture Computer Programming Inheritance 10 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved 순서 Inheritance

More information

Inheritance (Deitel chapter 9)

Inheritance (Deitel chapter 9) Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 12 continue 12.6 Case Study: Payroll System Using Polymorphism This section reexamines the CommissionEmployee- BasePlusCommissionEmployee hierarchy that we explored throughout

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section: 7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then

More information

Fig Fig Fig. 10.3

Fig Fig Fig. 10.3 CHAPTER 10 VIRTUAL FUNCTIONS AND POLYMORPHISM 1 Illustrations List (Main Page) Fig. 10.2 Fig. 10.3. Definition of abstract base class Shape. Flow of control of a virtual function call. CHAPTER 10 VIRTUAL

More information

Yanbu University College Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Lab Exercise 10

Yanbu University College Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Lab Exercise 10 Yanbu University College BACHELOR OF SCIENCE IN Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Third Semester Academic Year 2011 2012 Lab Exercise 10 Course Instructor: Mohammed

More information

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1 Inheritance & Polymorphism Recap Inheritance & Polymorphism 1 Introduction! Besides composition, another form of reuse is inheritance.! With inheritance, an object can inherit behavior from another object,

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 4&5: Inheritance Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword @override keyword

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(b): Abstract classes & Polymorphism Lecture Contents 2 Abstract base classes Concrete classes Polymorphic processing Dr. Amal Khalifa,

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4(b): Inheritance & Polymorphism Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 4(b): Subclasses and Superclasses OOP OOP - Inheritance Inheritance represents the is a relationship between data types (e.g. student/person)

More information

Solutions for H7. Lecture: Xu Ying Liu

Solutions for H7. Lecture: Xu Ying Liu Lecture: Xu Ying Liu 2011 0 Ex13.12 1 // Exercise 13.12 Solution: Date.h 2 // Date class definition. 3 #ifndef DATE_H 4 #define DATE_H 6 #include 7 using namespace std; 8 9 class Date 10 { 11

More information

BBM 102 Introduction to Programming II Spring Abstract Classes and Interfaces

BBM 102 Introduction to Programming II Spring Abstract Classes and Interfaces BBM 102 Introduction to Programming II Spring 2017 Abstract Classes and Interfaces 1 Today Abstract Classes Abstract methods Polymorphism with abstract classes Example project: Payroll System Interfaces

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Abstract Classes and Interfaces Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today Abstract Classes Abstract methods Polymorphism

More information

Chapter 9 - Object-Oriented Programming: Inheritance

Chapter 9 - Object-Oriented Programming: Inheritance Chapter 9 - Object-Oriented Programming: Inheritance 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship between Superclasses and Subclasses 9.5 Case Study: Three-Level

More information

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2) Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August Polymorphism, Dynamic Binding and Interface 2 4 pm Thursday 7/31/2008 @JD2211 1 Announcement Next week is off The class will continue on Tuesday, 12 th August 2 Agenda Review Inheritance Abstract Array

More information

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

Classes and Objects: A Deeper Look

Classes and Objects: A Deeper Look 1 8 Classes and Objects: A Deeper Look 1 // Fig. 8.1: Time1.java 2 // Time1 class declaration maintains the time in 24-hour format. 4 public class Time1 6 private int hour; // 0 2 7 private int minute;

More information

Programming in C# Inheritance and Polymorphism

Programming in C# Inheritance and Polymorphism Programming in C# Inheritance and Polymorphism C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data

More information

Chapter 7. Inheritance

Chapter 7. Inheritance Chapter 7 Inheritance Introduction to Inheritance Inheritance is one of the main techniques of objectoriented programming (OOP) Using this technique, a very general form of a class is first defined and

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 6 : Abstraction Lecture Contents 2 Abstract classes Abstract methods Case study: Polymorphic processing Sealed methods & classes

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More information

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name: CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : If a child overrides

More information

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes COMP200 - Object Oriented Programming: Test One Duration - 60 minutes Study the following class and answer the questions that follow: package shapes3d; public class Circular3DShape { private double radius;

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

9/10/2018 Programming Data Structures Inheritance

9/10/2018 Programming Data Structures Inheritance 9/10/2018 Programming Data Structures Inheritance 1 Email me if the office door is closed 2 Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor CSE 143 Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog Dog

More information

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy CISC181 Introduction to Computer Science Dr. McCoy Lecture 27 December 8, 2009 Object Oriented Programming Classes categorize entities that occur in applications. Class teacher captures commonalities of

More information

Making New instances of Classes

Making New instances of Classes Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using

More information

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: has a CSE143 Sp Student. CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches

More information

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More information

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: has a CSC Employee. Supervisor CSC 143 Object & Class Relationships Inheritance Reading: Ch. 10, 11 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Polymorphism 1 / 19 Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll.

More information

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1

More information

CSC330 Object Oriented Programming. Inheritance

CSC330 Object Oriented Programming. Inheritance CSC330 Object Oriented Programming Inheritance Software Engineering with Inheritance Can customize derived classes to meet needs by: Creating new member variables Creating new methods Override base-class

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype

More information

Object Oriented Relationships

Object Oriented Relationships Lecture 3 Object Oriented Relationships Group home page: http://groups.yahoo.com/group/java CS244/ 2 Object Oriented Relationships Object oriented programs usually consisted of a number of classes Only

More information

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance

More information

5/24/12. Introduction to Polymorphism. Chapter 8. Late Binding. Introduction to Polymorphism. Late Binding. Polymorphism and Abstract Classes

5/24/12. Introduction to Polymorphism. Chapter 8. Late Binding. Introduction to Polymorphism. Late Binding. Polymorphism and Abstract Classes Introduction to Polymorphism Chapter 8 Polymorphism and Abstract Classes Slides prepared by Rose Williams, Binghamton University There are three main programming mechanisms that constitute object-oriented

More information

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Define and discuss abstract classes Define and discuss abstract methods Introduce polymorphism Much of the information

More information

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming

More information

CS 209 Sec. 52 Spring, 2006 Lab 6 - B: Inheritance Instructor: J.G. Neal

CS 209 Sec. 52 Spring, 2006 Lab 6 - B: Inheritance Instructor: J.G. Neal CS 209 Sec. 52 Spring, 2006 Lab 6 - B: Inheritance Instructor: J.G. Neal Objectives. To gain experience with: 1. The creation of a simple hierarchy of classes. 2. The implementation and use of inheritance.

More information

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof Abstract Class Lecture 21 Based on Slides of Dr. Norazah Yusof 1 Abstract Class Abstract class is a class with one or more abstract methods. The abstract method Method signature without implementation

More information

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting Overview ITI 1121. Introduction to Computing II Rafael Falcon and Marcel Turcotte (with contributions from R. Holte) Electrical Engineering and Computer Science University of Ottawa Interface Abstract

More information

Programming in the large

Programming in the large Inheritance 1 / 28 Programming in the large Software is complex. Three ways we deal with complexity: Abstraction - boiling a concept down to its essential elements, ignoring irrelevant details Decomposition

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Chapter 19 - C++ Inheritance

Chapter 19 - C++ Inheritance Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 09 Inheritance What is Inheritance? In the real world: We have general terms for objects in the real

More information

Chapter 20 - C++ Virtual Functions and Polymorphism

Chapter 20 - C++ Virtual Functions and Polymorphism Chapter 20 - C++ Virtual Functions and Polymorphism Outline 20.1 Introduction 20.2 Type Fields and switch Statements 20.3 Virtual Functions 20.4 Abstract Base Classes and Concrete Classes 20.5 Polymorphism

More information

25. Generic Programming

25. Generic Programming 25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and

More information

Arrays OBJECTIVES. In this chapter you will learn:

Arrays OBJECTIVES. In this chapter you will learn: 7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then

More information

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1 Java and OOP Part 3 Extending classes OOP in Java : W. Milner 2005 : Slide 1 Inheritance Suppose we want a version of an existing class, which is slightly different from it. We want to avoid starting again

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java Chapter 3 Syntax, Errors, and Debugging Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different

More information

Software Development With Java CSCI

Software Development With Java CSCI Software Development With Java CSCI-3134-01 D R. R A J S I N G H Outline Week 8 Controlling Access to Members this Reference Default and No-Argument Constructors Set and Get Methods Composition, Enumerations

More information