Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Advanced Programming Inheritance (2). 2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing."— Presentation transcript:

1 1 Advanced Programming Inheritance (2)

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

5 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

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

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

10 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( ) {... }

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

12 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( ) {... } } 

13 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(); }

14 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( ) {... } }

15 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

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

17 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

18 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( ) {... } }

19 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 { } 22 33 11

20 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

21 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 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 23 public string LastName { get { return lastName; } set { lastName = value; } public string toString() { return FirstName + " " + LastName; } public abstract decimal Earnings(); }

24 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 25 public override decimal Earnings() { return WeeklySalary; } public override string ToString() { return "Boss: " + base.ToString(); }

26 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 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 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 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 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 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 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 33 return basePay + overtimePay; } public override string toString() { return "HourlyWorker: " + base.ToString(); }

34 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( 13.75 ), 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 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"; }

36 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").

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

38 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


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

Similar presentations


Ads by Google