1 Advanced Programming Inheritance (2). 2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
CS 211 Inheritance AAA.
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Object Oriented Concepts
Interfaces Need arising from software engineering –Disparate groups of programmers need to agree to a “contract” that spells out how their software interacts.
Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class.
Object Oriented Concepts Classes II. Object Oriented concepts Encapsulation Composition Inheritance Polymorphism.
Lecture 9 Polymorphism Richard Gesick.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Advanced Programming Lecture 5 Inheritance. 2 static Class Members Every object of a class has its own copy of all instance variables Sometimes it is.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base Classes and Derived Classes.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Peyman Dodangeh Sharif University of Technology Fall 2014.
1 Chapter 5 - Object-Oriented Programming 1 What is inheritance? Object-oriented systems allow classes to be defined in terms of other classes. Classes.
Module 10: Inheritance in C#. Overview Deriving Classes Implementing Methods Using Sealed Classes Using Interfaces Using Abstract Classes.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism.
CET203 SOFTWARE DEVELOPMENT Session 2B Constructors, Overriding and Overloading.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
O O P Polymorphism Object Oriented Programming Prepared & Presented by: dr.Ismail Farahat Chapter 4.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Object Oriented Programming
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Part 2 Outline 10.1Introduction 10.2 Derived-Class-Object to Base-Class-Object.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
1 Object- Oriented Programming (CS206) Object-Oriented Relationships.
C++ How to Program, 7/e.  There are cases in which it’s useful to define classes from which you never intend to instantiate any objects.  Such classes.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Lecture 12 Inheritance.
Inheritance and Polymorphism
Questions from last lesson
Chapter 9 – Object-Oriented Programming: Inheritance
 2002 Prentice Hall. All rights reserved.
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Programming Language
CIS 199 Final Review.
Programming in C# CHAPTER 5 & 6
Presentation transcript:

1 Advanced Programming Inheritance (2)

2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class, or subclass, or derived class. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class

3 The Object Class All classes in C# are derived from the Object class –if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class The Object class is therefore the ultimate root of all class hierarchies The Object class defines methods that will be shared by all objects in C#, e.g., –ToString: converts an object to a string representation –Equals: checks if two objects are the same –GetType: returns the type of a type of object A class can override a method defined in Object to have a different behavior, e.g., –String class overrides the Equals method to compare the content of two strings

4 References and Inheritance An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object Holiday day; day = new Holiday(); … day = new Christmas(); Holiday Christmas

Relationship between Base Classes and Derived Classes Use a point-circle hierarchy to represent relationship between base and derived classes The first thing a derived class does is call its base class’ constructor, either explicitly or implicitly override keyword is needed if a derived-class method overrides a base-class method If a base class method is going to be overridden it must be declared virtual

Constructors and Destructors in Derived Classes Instantiating a derived class, causes base class constructor to be called, implicitly or explicitly –Can cause chain reaction when a base class is also a derived class When a destructor is called, it performs its task and then invokes the derived class’ base class destructor

7 Calling Parent’s Constructor in a Child’s Constructor: the base Reference Constructors are not inherited, even though they have public visibility The first thing a derived class does is to call its base class’ constructor, either explicitly or implicitly –implicitly it is the default constructor –yet we often want to use a specific constructor of the parent to set up the "parent's part" of the object Syntax: use base public DerivedClass : BaseClass { public DerivedClass(…) : base(…) { // … } } r Example1 m See Book.cs m See Dictionary.cs m See BookConstructor.cs r Example2 m See FoodItem.cs m See Pizza.cs m See FoodAnalysis.cs

Calling Base Class Constructors Constructor declarations must use the base keyword A private base class constructor cannot be accessed by a derived class Use the base keyword to qualify identifier scope class Token { protected Token(string name) {... }... } class CommentToken: Token { public CommentToken(string name) : base(name) { }... } class Token { protected Token(string name) {... }... } class CommentToken: Token { public CommentToken(string name) : base(name) { }... }

9 Overloading vs. Overriding Overloading deals with multiple methods in the same class with the same name but different signatures Overloading lets you define a similar operation in different ways for different data Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overriding lets you define a similar operation in different ways for different object types

Defining Virtual Methods Syntax: Declare as virtual Virtual methods are polymorphic class Token {... public int LineNumber( ) {... } public virtual string Name( ) {... } class Token {... public int LineNumber( ) {... } public virtual string Name( ) {... }

Working with Virtual Methods To use virtual methods: –You cannot declare virtual methods as static –You cannot declare virtual methods as private

Working with Override Methods You can only override identical inherited virtual methods You must match an override method with its associated virtual method You can override an override method You cannot explicitly declare an override method as virtual You cannot declare an override method as static or private class Token {... public int LineNumber( ) {... } public virtual string Name( ) {... } } class CommentToken: Token {... public override int LineNumber( ) {... } public override string Name( ) {... } } class Token {... public int LineNumber( ) {... } public virtual string Name( ) {... } } class CommentToken: Token {... public override int LineNumber( ) {... } public override string Name( ) {... } } 

Practice: Implementing Methods class A { public virtual void M() { Console.Write("A"); } } class B: A { public override void M() { Console.Write("B"); } } class C: B { new public virtual void M() { Console.Write("C"); } } class D: C { public override void M() { Console.Write("D"); } static void Main() { D d = new D(); C c = d; B b = c; A a = b; d.M(); c.M(); b.M(); a.M(); } class A { public virtual void M() { Console.Write("A"); } } class B: A { public override void M() { Console.Write("B"); } } class C: B { new public virtual void M() { Console.Write("C"); } } class D: C { public override void M() { Console.Write("D"); } static void Main() { D d = new D(); C c = d; B b = c; A a = b; d.M(); c.M(); b.M(); a.M(); }

Quiz: Spot the Bugs class Base { public void Alpha( ) {... } public virtual void Beta( ) {... } public virtual void Gamma(int i) {... } public virtual void Delta( ) {... } private virtual void Epsilon( ) {... } } class Derived: Base { public override void Alpha( ) {... } protected override void Beta( ) {... } public override void Gamma(double d) {... } public override int Delta( ) {... } } class Base { public void Alpha( ) {... } public virtual void Beta( ) {... } public virtual void Gamma(int i) {... } public virtual void Delta( ) {... } private virtual void Epsilon( ) {... } } class Derived: Base { public override void Alpha( ) {... } protected override void Beta( ) {... } public override void Gamma(double d) {... } public override int Delta( ) {... } }

Abstract Classes and Methods Abstract classes –Cannot be instantiated –Used as base classes –Class definitions are not complete – derived classes must define the missing pieces –Can contain abstract methods and/or abstract properties Have no implementation Derived classes must override inherited abstract methods and properties to enable instantiation

Declaring Abstract Classes Use the abstract keyword abstract class Token {... } class Test { static void Main( ) { new Token( ); } abstract class Token {... } class Test { static void Main( ) { new Token( ); } Token { abstract } Token { abstract } An abstract class cannot be instantiated An abstract class cannot be instantiated 

Abstract Classes and Methods Concrete classes use the keyword override to provide implementations for all the abstract methods and properties of the base-class Any class with an abstract method or property must be declared abstract Even though abstract classes cannot be instantiated, we can use abstract class references to refer to instances of any concrete class derived from the abstract class

Implementing Abstract Methods Syntax: Use the abstract keyword Only abstract classes can declare abstract methods Abstract methods cannot contain a method body abstract class Token { public virtual string Name( ) {... } public abstract int Length( ); } class CommentToken: Token { public override string Name( ) {... } public override int Length( ) {... } } abstract class Token { public virtual string Name( ) {... } public abstract int Length( ); } class CommentToken: Token { public override string Name( ) {... } public override int Length( ) {... } }

Quiz: Spot the Bugs class First { public abstract void Method( ); } class First { public abstract void Method( ); } abstract class Second { public abstract void Method( ) { } } abstract class Second { public abstract void Method( ) { } } interface IThird { void Method( ); } abstract class Third: IThird { } interface IThird { void Method( ); } abstract class Third: IThird { }

Case Study: Inheriting Interface and Implementation Abstract base class Shape –Concrete virtual method Area (default return value is 0) –Concrete virtual method Volume (default return value is 0) –Abstract read-only property Name Class Point2 inherits from Shape –Overrides property Name (required) –Does NOT override methods Area and Volume Class Circle2 inherits from Point2 –Overrides property Name –Overrides method Area, but not Volume Class Cylinder2 inherits from Circle2 –Overrides property Name –Overrides methods Area and Volume

Case Study: Payroll System Base-class Employee –abstract –abstract method Earnings Classes that derive from Employee –Boss –CommissionWorker –PieceWorker –HourlyWorker All derived-classes implement method Earnings Driver program uses Employee references to refer to instances of derived-classes Polymorphism calls the correct version of Earnings

22 using System; public abstract class Employee { private string firstName; private string lastName; public Employee( string firstNameValue, string lastNameValue ) { FirstName = firstNameValue; LastName = lastNameValue; } public string FirstName { get { return firstName; } set { firstName = value; }

23 public string LastName { get { return lastName; } set { lastName = value; } public string toString() { return FirstName + " " + LastName; } public abstract decimal Earnings(); }

24 using System; public class Boss : Employee { private decimal salary; public Boss( string firstNameValue, string stNameValue, decimal salaryValue): base( firstNameValue,lastNameValue ) { WeeklySalary = salaryValue; } public decimal WeeklySalary { get { return salary; } set { if ( value > 0 ) salary = value; }

25 public override decimal Earnings() { return WeeklySalary; } public override string ToString() { return "Boss: " + base.ToString(); }

26 using System; public class CommissionWorker : Employee { private decimal salary; // base weekly salary private decimal commission; // amount paid per item sold private int quantity; // total items sold public CommissionWorker( string firstNameValue, string lastNameValue, decimal salaryValue, decimal commissionValue, int quantityValue ) : base( firstNameValue, lastNameValue ) { WeeklySalary = salaryValue; Commission = commissionValue; Quantity = quantityValue; } public decimal WeeklySalary { get { return salary; }

27 set { // ensure non-negative salary value if ( value > 0 ) salary = value; } public decimal Commission { get { return commission; } set { if ( value > 0 ) commission = value; } public int Quantity { get { return quantity; }

28 set { if ( value > 0 ) quantity = value; } public override decimal Earnings() { return WeeklySalary + Commission * Quantity; } public override string toString() { return "CommissionWorker: " + base.ToString(); } } // end class CommissionWorker

29 using System; public class PieceWorker : Employee { private decimal wagePerPiece; // wage per piece produced private int quantity; // quantity of pieces public PieceWorker( string firstNameValue, string lastNameValue, decimal wagePerPieceValue, int quantityValue ) : base( firstNameValue, lastNameValue ) { WagePerPiece = wagePerPieceValue; Quantity = quantityValue; } public decimal WagePerPiece { get { return wagePerPiece; } set { if ( value > 0 ) wagePerPiece = value; }

30 public int Quantity { get { return quantity; } set { if ( value > 0 ) quantity = value; } public override decimal Earnings() { return Quantity * WagePerPiece; } public override string ToString() { return "PieceWorker: " + base.ToString(); }

31 using System; public class HourlyWorker : Employee { private decimal wage; // wage per hour of work private double hoursWorked; // hours worked during week public HourlyWorker( string firstNameValue, string LastNameValue, decimal wageValue, double hoursWorkedValue ) : base( firstNameValue, LastNameValue ) { Wage = wageValue; HoursWorked = hoursWorkedValue; } public decimal Wage { get { return wage; } set { if ( value > 0 ) wage = value; }

32 public double HoursWorked { get { return hoursWorked; } set { if ( value > 0 ) hoursWorked = value; } public override decimal Earnings() { if ( HoursWorked <= 40 ) { return Wage * Convert.ToDecimal( HoursWorked ); } else { decimal basePay = Wage * Convert.ToDecimal( 40 ); decimal overtimePay = Wage * 1.5M * Convert.ToDecimal( HoursWorked - 40 );

33 return basePay + overtimePay; } public override string toString() { return "HourlyWorker: " + base.ToString(); }

34 public class EmployeesTest { public static void Main( string[] args ) { Boss boss = new Boss( "John", "Smith", 800 ); CommissionWorker commissionWorker = new CommissionWorker( "Sue", "Jones", 400, 3, 150 ); PieceWorker pieceWorker = new PieceWorker( "Bob","Lewis", Convert.ToDecimal( 2.5 ), 200 ); HourlyWorker hourlyWorker = new HourlyWorker( "Karen", "Price", Convert.ToDecimal( ), 50 ); Employee employee = boss; string output = GetString( employee ) + boss + " earned " + boss.Earnings().ToString( "C" ) + "\n\n"; employee = commissionWorker; output += GetString( employee ) + commissionWorker + " earned " + commissionWorker.Earnings().ToString( "C" ) + "\n\n"; employee = pieceWorker;

35 output += GetString( employee ) + pieceWorker + " earned " + pieceWorker.Earnings().ToString( "C" ) + "\n\n"; employee = hourlyWorker; output += GetString( employee ) + hourlyWorker + " earned " + hourlyWorker.Earnings().ToString( "C" ) +"\n\n"; MessageBox.Show( output, "Demonstrating Polymorphism", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main // return string that contains Employee information public static string GetString( Employee worker ) { return worker.ToString() + " earned " + worker.Earnings().ToString( "C" ) + "\n"; }

You have been provided with the following class that implements a phone number directory: public class PhoneBook { public boolean insert(String phoneNum, String name) {... } public String getPhoneNumber(String name) {... } public String getName(String phoneNum) {... } // other private fields and methods } PhoneBook does not accept phone numbers that begin with "0" or "1", that do not have exactly 10 digits. It does not allow duplicate phone numbers. insert() returns true on a successful phone number insertion, false otherwise. getPhoneNumber() and getName() return null if they cannot find the desired entry in the PhoneBook. Design and implement a subclass of PhoneBook called YellowPages (including all of the necessary fields and methods) that supports the following additional operations. Retrieve the total number of phone numbers stored in the directory. Retrieve the percentage of phone numbers stored in the directory that are "810" numbers (that have area code "810").

Design an abstract class named BankAccount with data: balance, number of deposits this month, number of withdrawals, annual interest rate, and monthly service charges. The class has constructor and methods: Deposit (amount) {add amount to balance and increment number of deposit by one}, Withdraw (amount) {subtract amount from balance and increment number of withdrawals by one}, CalcInterest() { update balance by amount = balance * (annual interest rate /12)}, and MonthlyPocess() {subtract the monthly service charge from balance, call calcInterest method, set number of deposit, number of withdrawals and monthly service charges to zero}. Next, design a SavingAccount class which inherits from BankAccount class. The class has Boolean status field to represent the account is active or inactive {if balance falls below $25}. No more withdrawals if account is inactive. The class has methods Deposit () {determine if account inactive then change the status after deposit above $25, then call base deposit method}, Withdraw() method check the class is active then call base method, and MonthlyProcess() {check if number of withdrawals more than 4, add to service charge $1 for each withdrawals above 4}

Consider designing and implementing a set of classes to represent books, library items, and library books. a) An abstract class library item contains two pieces of information: a unique ID (string) and a holder (string). The holder is the name of person who has checked out this item. The ID can not change after it is created, but the holder can change. b) A book class inherits from library item class. It contains data author and title where neither of which can change once the book is created. The class has a constructor with two parameters author and title, and two methods getAuthor() to return author value and getTitle() to return title value. c) A library book class is a book that is also a library item (inheritance). Suggest the required data and method for this class. d) A library is a collection of library books (Main class) which has operations: add new library book to the library, check out a library item by specifying its ID, determine the current holder of library book given its ID