CST141--Inheritance 2

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

CST141 Thinking in Objects Page 1

BBM 102 Introduction to Programming II Spring Inheritance

Inheritance and Polymorphism

CS111: PROGRAMMING LANGUAGE II

Java Object Oriented Design. CSC207 Fall 2014

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

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

Inheritance Motivation

CMSC 132: Object-Oriented Programming II

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CMSC 132: Object-Oriented Programming II

A A B U n i v e r s i t y

Data Structures (list, dictionary, tuples, sets, strings)

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Programming in C# Inheritance and Polymorphism

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

What are the characteristics of Object Oriented programming language?

CS-202 Introduction to Object Oriented Programming

Chapter 5 Object-Oriented Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

INHERITANCE. Spring 2019

OBJECT ORİENTATİON ENCAPSULATİON

The software crisis. 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.

CS 209 Sec. 52 Spring, 2006 Lab 5: Classes Instructor: J.G. Neal

CS 251 Intermediate Programming Inheritance

ITI Introduction to Computing II

Rules and syntax for inheritance. The boring stuff

PROGRAMMING LANGUAGE 2

What is Inheritance?

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

Java Programming Lecture 7

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 9 - Object-Oriented Programming: Inheritance

ITI Introduction to Computing II

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

CS111: PROGRAMMING LANGUAGE II

CLASSES AND OBJECTS IN JAVA

CS111: PROGRAMMING LANGUAGE II

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

JAVA MOCK TEST JAVA MOCK TEST II

Chapter 6 Introduction to Defining Classes

C++ Important Questions with Answers

Super-Classes and sub-classes

Object Oriented Programming. Java-Lecture 11 Polymorphism

CS260 Intro to Java & Android 03.Java Language Basics

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Inheritance -- Introduction

Practice for Chapter 11

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

OVERRIDING. 7/11/2015 Budditha Hettige 82

C08: Inheritance and Polymorphism

CS313D: ADVANCED PROGRAMMING LANGUAGE

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Inheritance (Deitel chapter 9)

C08: Inheritance and Polymorphism

Introduction to Object-Oriented Programming

Building Java Programs

Chapter 2a Class Relationships

Programming II (CS300)

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Inheritance CSC 123 Fall 2018 Howard Rosenthal

Inheritance (Part 2) Notes Chapter 6

Programming Exercise 14: Inheritance and Polymorphism

Advanced Placement Computer Science. Inheritance and Polymorphism

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

Chapter 9 - Object-Oriented Programming: Polymorphism

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

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

COMP 250 Fall inheritance Nov. 17, 2017

Java Magistère BFA

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

Cpt S 122 Data Structures. Inheritance

CSC9T4: Object Modelling, principles of OO design and implementation

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

Inheritance and Interfaces

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Self-review Questions

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Inheritance and Polymorphism

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Inheritance Introduction. 9.1 Introduction 361

CS111: PROGRAMMING LANGUAGE II

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 7. Inheritance

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

Everything is an object. Almost, but all objects are of type Object!

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Arrays Classes & Methods, Inheritance

Transcription:

- employeeid - hoursworked - checknumber payrate -+ employeeid setchecknumber() -+ hoursworked setemployeeid() -+ payrate sethoursworked() ed-oriented and Inheritance + setchecknumber() setpayrate() CST141 + setemployeeid() getchecknumber() OOP + sethoursworked() getemployeeid() -Oriented + setpayrate() gethoursworked() Programming is characterized by three features: + getchecknumber() getpayrate() Encapsulation + getgrosspay() getemployeeid() Inheritance + gethoursworked() New classes created from (extends) existing classes by absorbing (inheriting) + getpayrate() their attributes/properties (instance variables) and behaviors (methods) + getgrosspay() Code Polymorphism Duplication without Inheritance ability of an object to take on many forms; a common use occurs in OOP es that operate on similar entities often have many identical elements when a parent class reference is used to refer to a child class object Makes maintenance difficult/more work Code Introduces Duplication danger without of bugs Inheritance through incorrect maintenance es Code duplication that operate also on can similar carry entities over introducing often have problems many identical to the driver elements classes Makes maintenance difficult/more work Inheritance Introduces danger of bugs through incorrect maintenance When a new class is created, it inherits the instance variables and methods of any Code duplication also can carry over introducing problems to the driver classes previously defined superclass Inheritance This subclass gets its initial features from the direct superclass When An indirect a new superclass is created, is inherited it inherits from the two instance or more levels variables above and in methods a class hierarchy of any previously defined superclass Subclass This subclass gets its initial features from the direct superclass subclass is usually larger than its superclass An indirect superclass is inherited from two or more levels above in a class hierarchy Because it adds instance variables and methods of its own to those of the superclass Subclass Also subclass it is possible is usually to define larger than additions its superclass to, or replacements for, inherited superclass Because features it adds instance variables and methods of its own to those of the It is superclass more specific than the superclass Also refore it is possible it has a to smaller define number additions of to, situations or replacements in which it for, can inherited be usedsuperclass features Superclass It is more specific than the superclass Each superclass exists at the top of a hierarchical relationship with its subclasses refore it has a smaller number of situations in which it can be used A superclass may have several direct subclasses which inherit its features A subclass Superclass to one superclass may be a superclass to other subclasses Each superclass exists at the top of a hierarchical relationship with its subclasses A Payroll Hierarchy A superclass may have several direct subclasses which inherit its features A A College subclass Inheritance to one superclass Hierarchy may be a superclass to other subclasses CST141--Inheritance HourlySalaryCheck Page 1 1 4 34 1 5 5 6 6 7 7 8 9 108 9 10 11 4 11 1 5 A Has Payroll a Hierarchy vs. Is a A se College two Inheritance phrases that Hierarchy express the nature of relationships and class attributes between superclasses and subclasses in inheritance: Has A a class to vs. its Is own a attributes ( has a ) se A subclass two phrases to the that superclass express from the nature which it of inherits relationships additional and attributes class attributes ( is a ) between superclasses and subclasses in inheritance: Has a Relationships A class to its own attributes ( has a ) Has a relationship expresses the attributes (instance variables) within the class A subclass to the superclass from which it inherits additional attributes ( is a ) (called composition) Has A class a has Relationships a(n) attribute, i.e. Has HourlySalaryCheck a relationship expresses has an HoursWorked, the attributes (instance has a Pay variables) Rate within the class (called CommunityMember composition) has a First Name, has a Last Name, has an Address, etc. A class has a(n) attribute, i.e. Is a Relationships HourlySalaryCheck has an HoursWorked, has a Pay Rate Is a relationship expresses inheritance CommunityMember has a First Name, has a Last Name, has an Address, etc. Subclass is a superclass, i.e.

11 CST141--Inheritance Page setannualsalary() getannualsalary() getgrosspay() 1 13 17 18 19 0 1 14 15 3 16 4 5 6 17 18 19 0 1 7 3 1 HourlySalaryCheck CommunityMember has a First Name, has a Last Name, has an Address, etc. Is hoursworked a Relationships Is payrate a relationship expresses inheritance sethoursworked() Subclass is a superclass, i.e. setpayrate() AnnualSalaryCheck is a PayrollCheck gethoursworked() And has all the attributes of a PayrollCheck, i.e. if PayrollCheck has a Check getpayrate() Number attribute, AnnualSalaryCheck does also getgrosspay() Teacher is a Faculty And has all the attributes of a Faculty member, i.e. if Faculty has a Rank attribute, Teacher does also PayrollCheck.java Libraries New classes inherit features from an organization's own class library PayrollCheck.java When developing a new class: PayrollCheck.java First try to find a place for it in the 3) existing inheritance hierarchy PayrollCheck.java Only if it does not fit into the current 4) class library structure should it be the beginning of a new inheritance hierarchy segment PayrollCheck.java 5) Libraries Java A PayrollLedger API uses inheritance Hierarchy to build its vast library collection of classes Keyword extends Declares that this class is a direct subclass of the superclass that is named following the keyword extends class inherits all public and protected members (instance variables and methods) of the superclass A class may extend (inherit) directly only from one class (its direct superclass) Keyword extends public class SubName extends DirectSuperName { Examples: public class HourlySalaryCheck extends PayrollCheck { public class Faculty extends Employee { Superclass Constructor Call Subclass constructors always must contain a call to super (to its direct superclass constructor method), or... If none is written, the compiler inserts one (an implicit call without parameters) Works only if superclass has a constructor without parameters Superclass Constructor Call Must be the first statement in the body of the subclass constructor public AnnualSalaryCheck(int checknumber, int employeeid, double annualsalary) { super(checknumber, employeeid); setannualsalary(annualsalary); } Calling Superclass Methods public members of a superclass are callable from the subclass [super.]superclassmethod(parameters)

[super.]superclassmethod(parameters) CST141--Inheritance Keyword super is not required (and is not standard usage) unless overriding Page 3 7 8 8 9 30 9 30 31 3 33 34 35 36 31 37 3 33 34 35 36 38 37 superclass methods Examples: super.tostring() super.getemployeeid; Calling getemployeeid; Superclass Methods public members of a superclass are callable from the subclass Method Overriding To [super.]superclassmethod(parameters) modify the implementation of an inherited method in a subclass Keyword super is not required (and is not standard usage) unless overriding public superclass String methods tostring() Examples: { super.tostring() return super.tostring() super.getemployeeid; + "\nhours worked: " + gethoursworked() getemployeeid; + "\npay rate: " + getpayrate() + "\ngross pay: " + getgrosspay(); Method } Overriding To modify the implementation of an inherited method in a subclass Method Overriding Superclass public String method tostring() must be public (accessible) { A private superclass method cannot be overridden Methods return that super.tostring() are static can be inherited but not overridden To + access "\nhours a hidden worked: (because " + gethoursworked() a method of the same name exists in the subclass) static + "\npay method rate: in a " superclass, + getpayrate() use the class name, e.g. SuperclassName.staticMethodName() + "\ngross pay: " + getgrosspay(); } @Override Annotation Method Placing Overriding @Override before a subclass method denotes that the method must override the method in the superclass Superclass method must be public (accessible) A private superclass method cannot be overridden @Overrides Methods that are static can be inherited but not overridden public type subclassmethodname() To access a hidden (because a method of the same name exists in the subclass) { static method in a superclass, use the class name, e.g. SuperclassName.staticMethodName() @Overrides public @Override String tostring() Annotation Placing { @Override before a subclass method denotes that the method must override the method in the superclass HourlySalaryCheck.java HourlySalaryCheck.java @Overrides public type subclassmethodname() HourlySalaryCheck.java 3) { HourlySalaryCheck.java 4) @Overrides Instantiate an HourlyPayrollCheck object public String tostring() { DecimalFormat used to create objects used to format numbers for output Stored in the java.text package import java.text.decimalformat; DecimalFormat objectname = new DecimalFormat("formatString"); formatstring argument is a String of characters that specify how numbers will be formatted DecimalFormat Example 1:

Rounded to the nearest CST141--Inheritance 39 DecimalFormat integer 3) Page 4 Example : DecimalFormat twodecimals = new DecimalFormat("0.00"); String argument "0.00" specifies that the number will display: formatstring At least one digit argument to the is left a String of the of decimal characters pointthat specify how numbers will be formatted Exactly two digits (rounded) to the right of the decimal point 38 40 DecimalFormat 4) Example functionality 1: of Examples 1 and can be combined to add commas to the two decimals DecimalFormat rounded: commaformat = new DecimalFormat("#,##0"); DecimalFormat String argument grosspayformat "#,##0" specifies = new that DecimalFormat("#,##0.00"); the number will display: A With floating commas dollar at signthe could thousands, be inserted millions, prior etc. to the rest of the format string: DecimalFormat Only if number grosspayformat is 1000 or greater; = new otherwise DecimalFormat("$#,##0.00"); printing of leading zeros and commas are from the 10 s position to the left are suppressed 41 Rounded format Method to the nearest integer Formats a numeric value according to the DecimalFormat object's format string 39 Takes DecimalFormat one variable/value (either float 3) or double) as its single argument Example : decimalformat.format(float/double); DecimalFormat twodecimals = new DecimalFormat("0.00"); String argument "0.00" specifies that the number will display: JOptionPane.showMessageDialog(null, At least one digit to the left of the decimal grosspayformat.format(grosspay)); point Exactly two digits (rounded) to the right of the decimal point 4 Driver1.java (Version 40 DecimalFormat 4) 43 Driver1.java functionality of (Version Examples 1 and can be combined to add commas to the two 44 45 46 A PayrollLedger decimals rounded: Hierarchy DecimalFormat grosspayformat = new DecimalFormat("#,##0.00"); A AnnualSalaryCheck.java floating dollar sign could be inserted prior to the rest of the format string: AnnualSalaryCheck.java DecimalFormat grosspayformat = new DecimalFormat("$#,##0.00"); 41 47 48 49 50 51 4 5 43 44 45 46 47 53 48 49 50 51 5 54 55 AnnualSalaryCheck.java format Method 3) Formats a numeric value according to the DecimalFormat object's format string AnnualSalaryCheck.java 4) Takes one variable/value (either float or double) as its single argument AnnualSalaryCheck.java 5) decimalformat.format(float/double); AnnualSalaryCheck.java 6) Driver1.java JOptionPane.showMessageDialog(null, grosspayformat.format(grosspay)); Extendible es Software is extendible when it can be easily updated and reused to do something that the original author never imagined Extendibility is enhanced by: Loose coupling few connections cohesion classes with one single, well defined entity Responsibility-driven design in which classes are responsible for manipulating their own data Extendible es When developing a new class, look to find a place where it can extend another class in the existing inheritance hierarchy Sometime superclasses in an inheritance hierarchy only serve to support subclasses Such superclasses are called abstract classes (never have objects instantiated from them) A PayrollLedger Hierarchy MiniQuiz Define a new class ConsultantCheck that extends from PayrollCheck for consultants who receive a check based on a one-time payment

CST141--Inheritance Page 5 7 73 71 73 7 73 74 74 74 75 75 76 76 77 75 77 76 77 78 78 79 79 78 79 80 80 80 81 81 81 8 8 83 83 84 8 84 Driver1.java Driver1.java superclass of all classes (either direct or indirect) is from the Java API If a class definition does not explicitly extend another class, it extends superclass of all classes (either direct or indirect) is from the Java API directly If a class definition does not explicitly extend another class, it extends following two class headers effectively are identical: directly public class PayrollCheck { following superclasstwo of class all classes headers (either effectively direct or are indirect) identical: is from the Java API public class PayrollCheck extends public If a class definition PayrollCheck does { not explicitly extend another class, it extends { public directly class PayrollCheck extends { following two class headers effectively are identical: public class PayrollCheck { As a result all classes inherit eleven (1 public methods from including: public tostring(), class PayrollCheck equals() and extends hashcode() As a result all classes inherit eleven (1 public methods from including: Additionally { classes from the Java API use inheritance extensively and extend also tostring(), equals() and hashcode() from Additionally class (directly or indirectly) classes from the Java API use inheritance extensively and extend also As A from PayrollLedger a result class all classes Hierarchy (directly inherit or eleven indirectly) (1 public methods from including: A PayrollCheck.java PayrollLedger tostring(), equals() Hierarchy and hashcode() Additionally classes from the Java API use inheritance extensively and extend also PayrollCheck.java from tostring() class Method (directly of or indirectly) Method tostring() tostring() Method is a member of of class that returns a String representation of an object Method tostring() is a member of class that returns a String representation of All classes inherit the tostring() method either directly or indirectly from an object May be called or overridden All classes inherit the tostring() method either directly or indirectly from Returns the class name of which the object is an instance and a hash code (start May be called or overridden address where the object is stored in memory in hexadecimal), e.g. Returns the class name of which the object is an instance and a hash code (start HourlySalaryCheck@15037e5 address where the object is stored in memory in hexadecimal), e.g. PayrollCheck.java HourlySalaryCheck@15037e5 (.tostring() Page 5) PayrollCheck.java Advantages of Inheritance (.tostring() (so far) Page 5) Advantages Avoiding code of duplication Inheritance (so far) Code reuse Avoiding code duplication Easier maintenance Code reuse Extendibility Easier maintenance Extendibility Subtyping Subtyping Types defined by a subclass definition actually are subtypes of their superclass If HourlySalaryCheck and AnnualSalaryCheck classes are extensions of class Types defined by a subclass definition actually are subtypes of their superclass PayrollCheck: If HourlySalaryCheck and AnnualSalaryCheck classes are extensions of class superclass object: PayrollCheck: PayrollCheck pay; superclass object: Can be instantiated by calling its subtype constructor: PayrollCheck pay; pay = new AnnualSalaryCheck(); Can be instantiated by calling its subtype constructor: Or in a single statement: pay = new AnnualSalaryCheck(); PayrollCheck pay = new AnnualSalaryCheck(); Or in a single statement: Subtyping PayrollCheck pay = new AnnualSalaryCheck(); Subtyping Now the subtyped object can differentiate between getgrosspay() methods of HourlySalaryCheck and AnnualSalaryCheck classes when called: Now the subtyped object can differentiate between getgrosspay() methods of JOptionPane.showMessageDialog( null, pay.getgrosspay() ); HourlySalaryCheck and AnnualSalaryCheck classes when called: This is an example of polymorphism (meaning many shapes or many forms ) JOptionPane.showMessageDialog( null, pay.getgrosspay() ); In this case the method behavior changes based upon which constructor was used This is an example of polymorphism (meaning many shapes or many forms ) to instantiate it In this case the method behavior changes based upon which constructor was used Driver.java to instantiate it Driver.java Driver.java ArrayList Used ArrayList to create a list of items in a flexible-sized collection

CST141--Inheritance Page 6 8 83 84 85 86 87 88 89 90 91 ArrayList Used to create a list of items in a flexible-sized collection capacity of an ArrayList object is initialized to start at ten (10) elements but grows as items are added to it ArrayList class has a whole series of methods of its own which can be used to automatically manipulate objects instantiated from it Found in the java.util package of the Java API library: import java.util.arraylist; ArrayList 3) Format to declare an ArrayList object: ArrayList<type> objectname; private ArrayList<String> departmentlist; ArrayList is a generic class requiring a subtype specified as a parameter Enclosed in <chevrons>, e.g. <angle brackets> example data field above departmentlist is called an ArrayList of Strings Instantiating ArrayList s Similar syntax to that which is used when instantiating objects Includes the second type parameter enclosed in <chevrons> objectname = new ArrayList<type>(); departmentlist = new ArrayList<String>(); Instantiating ArrayList s Format to declare and instantiate the object in a single statement: ArrayList<type> objectname = new ArrayList<type>(); ArrayList<String> departmentlist = new ArrayList<String>(); add() Method for ArrayList Appends this element (object) to the end of the ArrayList collection arraylist.add(object); object represents the value added as a new element to the ArrayList collection departmentlist.add("computer"); size() Method for ArrayList Returns an int which is the number of elements in the ArrayList collection arraylist.size() JOptionPane.showMessageDialog( null, departmentlist.size() ); get() Method for ArrayList Retrieves an individual element from the specified position in ArrayList collection arraylist.get(index) index is an int between zero (0) and one less than the number of items in the

Returns an int which is the number of elements in the ArrayList collection CST141--Inheritance Page 7 arraylist.size() JOptionPane.showMessageDialog( null, departmentlist.size() ); 91 9 93 94 95 96 97 98 get() Method for ArrayList Retrieves an individual element from the specified position in ArrayList collection arraylist.get(index) index is an int between zero (0) and one less than the number of items in the ArrayList JOptionPane.showMessageDialog(null, departmentlist.get(index) ); element is not removed from the collection indexof() Method for ArrayList Searches for first occurrence of the object argument in the ArrayList collection tests for an equal to (==) condition method returns either : An int which is the index representing its position in the ArrayList collection Or -1 if the search criteria value is not found indexof() Method for ArrayList arraylist.indexof(object) index = departmentlist.indexof("computer"); remove() Method for ArrayList Deletes an individual element from the specified position in ArrayList collection All elements after the deleted item move up one element to fill the gap remove() Method for ArrayList arraylist.remove(index); index is an integer between zero (0) and one less than the number of elements in the ArrayList departmentlist.remove(index); MiniQuiz No. Open the college project and create a new class Alum that extends from CommunityMember re are two data fields: gradyear the year the alumnus or alumna graduated degree the degree granted to the alumnus or alumna An ArrayList of Strings stores valid degrees including B.A., B.S., M.A., M.S. and PH.D Alum.java MiniQuiz No. constructor: Takes two Strings for firstname and lastname, an int for gradyear and a String for degree Passes firstname and lastname to the superclass constructor Instantiates the ArrayList and assigns the values ( B.A., B.S., M.A., M.S. and PH.D )