CST141--Inheritance 2

Size: px
Start display at page:

Download "CST141--Inheritance 2"

Transcription

1 - 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 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.

2 11 CST141--Inheritance Page setannualsalary() getannualsalary() getgrosspay() 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)

3 [super.]superclassmethod(parameters) CST141--Inheritance Keyword super is not required (and is not standard usage) unless overriding Page 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(); Annotation Method Placing 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 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. String tostring() Annotation Placing before a subclass method denotes that the method must override the method in the superclass HourlySalaryCheck.java public type subclassmethodname() HourlySalaryCheck.java 3) { HourlySalaryCheck.java 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:

4 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 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 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"); 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

5 CST141--Inheritance Page 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

6 CST141--Inheritance Page 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

7 Returns an int which is the number of elements in the ArrayList collection CST141--Inheritance Page 7 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 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 )

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

CST141 Thinking in Objects Page 1

CST141 Thinking in Objects Page 1 CST141 Thinking in Objects Page 1 1 2 3 4 5 6 7 8 Object-Oriented Thinking CST141 Class Abstraction and Encapsulation Class abstraction is the separation of class implementation from class use It is not

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

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 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

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

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

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

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

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

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

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 10: I n h e r i t a n c e Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

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

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

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

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

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

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

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

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

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

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance CS257 Computer Science I Kevin Sahr, PhD Lecture 10: Inheritance 1 Object Oriented Features For a programming language to be called object oriented it should support the following features: 1. objects:

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

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

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

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

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

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

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

CS 209 Sec. 52 Spring, 2006 Lab 5: Classes Instructor: J.G. Neal CS 209 Sec. 52 Spring, 2006 Lab 5: Classes Instructor: J.G. Neal Objectives. To gain experience with: 1. The definition and use of a class to represent a real-world type of entity (an employee). 2. Adding

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

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

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

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

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

Java Programming Lecture 7

Java Programming Lecture 7 Java Programming Lecture 7 Alice E. Fischer Feb 16, 2015 Java Programming - L7... 1/16 Class Derivation Interfaces Examples Java Programming - L7... 2/16 Purpose of Derivation Class derivation is used

More information

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

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation

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

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

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

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018 Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Java Inheritance Example I Visibility peekabo Constructors Fontys Hogeschool voor Techniek en Logistiek January 11, 2018

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

CLASSES AND OBJECTS IN JAVA

CLASSES AND OBJECTS IN JAVA Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class

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

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

JAVA MOCK TEST JAVA MOCK TEST II

JAVA MOCK TEST JAVA MOCK TEST II http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

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

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

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

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

More information

C08: Inheritance and Polymorphism

C08: Inheritance and Polymorphism CISC 3120 C08: Inheritance and Polymorphism Hui Chen Department of Computer & Information Science CUNY Brooklyn College 2/26/2018 CUNY Brooklyn College 1 Outline Recap and issues Project progress? Practice

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

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

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017 Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 /FHTenL Inheritance and February 10, 2017 1/45 Topics

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

C08: Inheritance and Polymorphism

C08: Inheritance and Polymorphism CISC 3120 C08: Inheritance and Polymorphism Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/19/2017 CUNY Brooklyn College 1 Outline Recap and issues Project progress? Practice

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

Building Java Programs

Building Java Programs Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4, 16.4-16.5 2 A tree set Our SearchTree class is essentially a set. operations: add, remove, contains, size, isempty similar

More information

Chapter 2a Class Relationships

Chapter 2a Class Relationships Data Structures for Java William H. Ford William R. Topp Chapter 2a Class Relationships Bret Ford 2005, Prentice Hall Wrapper Classes Convert a value of primitive type to an object. Supply methods to access

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

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

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. Inf1-OP Inheritance UML Class Diagrams UML: language for specifying and visualizing OOP software systems UML class diagram: specifies class name, instance variables, methods,... Volker Seeker, adapting

More information

Inheritance CSC 123 Fall 2018 Howard Rosenthal

Inheritance CSC 123 Fall 2018 Howard Rosenthal Inheritance CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Defining what inheritance is and how it works Single Inheritance Is-a Relationship Class Hierarchies Syntax of Java Inheritance The super Reference

More information

Inheritance (Part 2) Notes Chapter 6

Inheritance (Part 2) Notes Chapter 6 Inheritance (Part 2) Notes Chapter 6 1 Object Dog extends Object Dog PureBreed extends Dog PureBreed Mix BloodHound Komondor... Komondor extends PureBreed 2 Implementing Inheritance suppose you want to

More information

Programming Exercise 14: Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.

More information

Advanced Placement Computer Science. Inheritance and Polymorphism

Advanced Placement Computer Science. Inheritance and Polymorphism Advanced Placement Computer Science Inheritance and Polymorphism What s past is prologue. Don t write it twice write it once and reuse it. Mike Scott The University of Texas at Austin Inheritance, Polymorphism,

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

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

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

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics Inf1-OP Inheritance Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 12, 2018 UML Class Diagrams UML: language for specifying and visualizing OOP software

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

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

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

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

CSC9T4: Object Modelling, principles of OO design and implementation

CSC9T4: Object Modelling, principles of OO design and implementation CSC9T4: Object Modelling, principles of OO design and implementation CSCU9T4 Spring 2016 1 Class diagram vs executing program The class diagram shows us a static view of the responsibilities and relationships

More information

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

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

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

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

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class? Which statement is correct about overriding private methods in the super class? Peer Instruction Polymorphism Please select the single correct answer. A. Any derived class can override private methods

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

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

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

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass Inheritance and Polymorphism Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism Inheritance (semantics) We now have two classes that do essentially the same thing The fields are exactly

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

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

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

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

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

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

Everything is an object. Almost, but all objects are of type Object! Everything is an object Almost, but all objects are of type Object! In Java, every class is actually a subclass of Object...or has a superclass which has Object as superclass... There is a class called

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Arrays Classes & Methods, Inheritance

Arrays Classes & Methods, Inheritance Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value

More information