1 Advanced Programming Lecture 5 Inheritance. 2 static Class Members Every object of a class has its...

85
1 Advanced Programming Lecture 5 Inheritance

Transcript of 1 Advanced Programming Lecture 5 Inheritance. 2 static Class Members Every object of a class has its...

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

1

Advanced Programming

Lecture 5

Inheritance

Page 2: 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.

2

static Class Members

• Every object of a class has its own copy of all instance variables

• Sometimes it is useful if all instances of a class share the same copy of a variable

• Declare variables using keyword static to create only one copy of the variable at a time (shared by all objects of the type)

• Scope may be defined for static variables (public, private, etc.)

Page 3: 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.

3

using System; public class Employee { private string firstName; private string lastName; private static int count; public Employee( string fName, string lName ){ firstName = fName;lastName = lName; ++count; Console.WriteLine( "Employee object constructor: " +firstName + " " + lastName + "; count = " + Count ); }~Employee() { --count;Console.WriteLine( "Employee object destructor: " +firstName + " " + lastName + "; count = " + Count );}

Page 4: 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.

4 public string FirstName { get { return firstName; } } public string LastName { get { return lastName; } } public static int Count { get { return count; } } } // end class Employee

Page 5: 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.

5

using System; class StaticTest { static void Main( string[] args ) {Console.WriteLine( "Employees before instantiation: " +Employee.Count + "\n" );

Employee employee1 = new Employee( "Susan", "Baker" );Employee employee2 = new Employee( "Bob", "Jones" );Console.WriteLine( "\nEmployees after instantiation: " +"Employee.Count = " + Employee.Count + "\n" );Console.WriteLine( "Employee 1: " + employee1.FirstName + " " +employee1.LastName +"\nEmployee 2: " + employee2.FirstName + " + employee2.LastName + "\n" ); employee1 = null; employee2 = null;

Page 6: 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.

636 Console.WriteLine( 37 "\nEmployees after garbage collection: " +38 Employee.Count );39 }40 }

Employees before instantiation: 0 Employee object constructor: Susan Baker; count = 1Employee object constructor: Bob Jones; count = 2 Employees after instantiation: Employee.Count = 2 Employee 1: Susan BakerEmployee 2: Bob Jones Employee object destructor: Bob Jones; count = 1Employee object destructor: Susan Baker; count = 0 Employees after garbage collection: 0

Page 7: 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.

7

Inheritance

Classes are created by absorbing the methods and variables of an existing class– It then adds its own methods to enhance its capabilities

– This class is called a derived class because it inherits methods and variables from a base class

– Objects of derived class are objects of base class, but not vice versa

– “Is a” relationship: derived class object can be treated as base class object

– “Has a” relationship: class object has object references as members

– A derived class can only access non-private base class members unless it inherits accessor funcitons

Page 8: 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.

8

Base Classes and Derived Classes

• Every derived-class is an object of its base class• Inheritance forms a tree-like hierarchy• To specify class one is derived from class two

– class one : two

• Composition:– Formed by “has a” relationships

• Constructors are not inherited

Page 9: 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.

9

Base Classes and Derived Classes

Base class Derived classes Student GraduateStudent

UndergraduateStudent

Shape Circle Triangle Rectangle

Loan CarLoan HomeImprovementLoan MortgageLoan

Employee FacultyMember StaffMember

Account CheckingAccount SavingsAccount

Fig. 9.1 Inheritance examples.

Page 10: 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.

10

Base Classes and Derived Classes

CommunityMemeber

Employee Student Alumnus

Faculty Staff

Administrator Teacher

Page 11: 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.

11

Base Classes and Derived Classes

Shape

TwoDimensionalShape ThreeDimensionalShape

Sphere Cube CylinderTriangleSquareCircle

Page 12: 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.

12

Point.cs

using System;public class Point {private int x, y;

public Point() {

}public Point( int xValue, int yValue ) {

X = xValue; Y = yValue; }public int X { get { return x; }

Page 13: 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.

13

set { x = value; // no need for validation } } // end property X public int Y { get { return y; } set { y = value; // no need for validation } } // end property Y

public override string ToString() { return "[" + x + ", " + y + "]"; } } // end class Point

Page 14: 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.

14

Circle2.cs

using System; class Circle : Point { private double radius; // Circle2's radius public Circle() { } public Circle( int xValue, int yValue, double radiusValue ) { x = xValue; y = yValue; Radius = radiusValue; } public double Radius { get { return radius; }

Declare class Circle to derive from class Point

Page 15: 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.

15

Circle2.cs

set { if ( value >= 0 ) radius = value; } } // end property Radius public double Diameter() { return radius * 2; } public double Circumference() { return Math.PI * Diameter(); } public virtual double area() { return Math.PI * Math.Pow( radius, 2 ); } public override string ToString() { return "Center = [" + x + ", " + y + "]" + "; Radius = " + radius; } } // end class Circle2

Page 16: 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.

16

Page 17: 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.

17

protected and internal Members

• protected members– Can be accessed by base class or any class derived from that

base class

• internal members:– Can only be accessed by classed declared in the same

assembly

• Overridden base class members can be accessed:– base.member

Page 18: 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.

18

Point2.cs

using System;

public class Point2 { protected int x, y; public Point2() { } public Point2( int xValue, int yValue ) { X = xValue; Y = yValue; } public int X { get { return x; }

Page 19: 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.

19

set { x = value; // no need for validation } } // end property X public int Y { get { return y; } set { y = value; // no need for validation } } // end property Y public override string ToString() { return "[" + x + ", " + y + "]"; }

Page 20: 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.

20

Circle3.cs

using System; public class Circle3 : Point2 { private double radius; // Circle's radius public Circle3() { // implicit call to Point constructor occurs here } // constructor public Circle3( int xValue, int yValue, double radiusValue ) { // implicit call to Point constructor occurs here x = xValue; y = yValue; Radius = radiusValue; } // property Radius public double Radius { get { return radius; }

Page 21: 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.

21

Circle3.cs

set { if ( value >= 0 ) radius = value; } } // end property Radiuspublic double Diameter() { return radius * 2; } public double Circumference() { return Math.PI * Diameter(); } // calculate Circle area public virtual double Area() { return Math.PI * Math.Pow( radius, 2 ); } public override string ToString() { return "Center = [" + x + ", " + y + "]" + "; Radius = " + radius; } } // end class Circle3

Page 22: 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.

22 using System; using System.Windows.Forms; // CircleTest3 class definition class CircleTest3 { // main entry point for application static void Main( string[] args ){ // instantiate Circle3 Circle3 circle = new Circle3( 37, 43, 2.5 ); string output = "X coordinate is " + circle.X + "\n" + "Y coordinate is " + circle.Y + "\nRadius is " + circle.Radius; // set Circle3's x-y coordinates and radius to new values circle.X = 2; circle.Y = 2; circle.Radius = 4.25; // display Circle3's string representation output += "\n\n" + "The new location and radius of circle are " + "\n" + circle + "\n"; // display Circle3's Diameter output += "Diameter is " + String.Format( "{0:F}", circle.Diameter() ) + "\n";

Page 23: 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.

23 // display Circle3's Circumference output += "Circumference is " + String.Format( "{0:F}", circle.Circumference() ) + "\n"; // display Circle3's Area output += "Area is " + String.Format( "{0:F}", circle.Area() ); MessageBox.Show( output, "Demonstrating Class Circle3" ); } // end method Main } // end class CircleTest3

Page 24: 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.

Case Study: Three-Level Inheritance Hierarchy

• Three-level inheritance example:

– Class Cylinder inherits from class Circle

– Class Circle inherits from class Point

Page 25: 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.

25

using System;

// Cylinder class definition inherits from Circle4

public class Cylinder : Circle4

{

private double height;

// default constructor

public Cylinder( int xValue, int yValue, double radiusValue,

double heightValue ) : base( xValue, yValue, radiusValue )

{

Height = heightValue; // set Cylinder height

}

// property Height

public double Height

{

get

{

return height;

}

set

{

if ( value >= 0 ) // validate height

height = value;

Page 26: 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.

26

}

} // end property Height

// override Circle4 method Area to calculate Cylinder area

public override double Area()

{

return 2 * base.Area() + base.Circumference() * Height;

}

// calculate Cylinder volume

public double Volume()

{

return base.Area() * Height;

}

// convert Cylinder to string

public override string ToString()

{

return base.ToString() + "; Height = " + Height;

}

} // end class Cylinder

Page 27: 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.

27 using System; using System.Windows.Forms; // CylinderTest class definition class CylinderTest { // main entry point for application static void Main( string[] args ) { // instantiate object of class Cylinder Cylinder cylinder = new Cylinder(12, 23, 2.5, 5.7); // properties get initial x-y coordinate, radius and height string output = "X coordinate is " + cylinder.X + "\n" + "Y coordinate is " + cylinder.Y + "\nRadius is " + cylinder.Radius + "\n" + "Height is " + cylinder.Height; // properties set new x-y coordinate, radius and height cylinder.X = 2; cylinder.Y = 2; cylinder.Radius = 4.25; cylinder.Height = 10; // get new x-y coordinate and radius output += "\n\nThe new location, radius and height of " + "cylinder are\n" + cylinder + "\n\n"; // display Cylinder's Diameter output += "Diameter is " + String.Format( "{0:F}", cylinder.Diameter() ) + "\n";

Page 28: 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.

28 // display Cylinder's Circumference output += "Circumference is " + String.Format( "{0:F}", cylinder.Circumference() ) + "\n"; // display Cylinder's Area output += "Area is " + String.Format( "{0:F}", cylinder.Area() ) + "\n"; // display Cylinder's Volume output += "Volume is " + String.Format( "{0:F}", cylinder.Volume() ); MessageBox.Show( output, "Demonstrating Class Cylinder" ); } // end method Main } // end class CylinderTest

Page 29: 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.

29

Example

• Imagine a publishing company that markets both Book and audio-CD versions of its works. Create a class publication that stores the title (string), price (float) and sales (array of three floats) of a publication.

• This class is used as base class for two classes: Book which has page count (int) and audio-CD which has playing time in minutes (float). Each of these three classes should have a get_data() and display_data() methods.

• Write a Main class to create Book and audio-CD objects, asking user to fill in their data with get_data( ) method, and then displaying data with display_data( ) method.

Page 30: 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.

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

Page 31: 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.

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

Page 32: 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.

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

Page 33: 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.

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

Page 34: 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.

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

Page 35: 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.

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

Page 36: 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.

36

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

Page 37: 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.

37

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

Page 38: 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.

38

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

Page 39: 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.

39

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

Page 40: 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.

40

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

Page 41: 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.

41 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; }

Page 42: 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.

42

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

Page 43: 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.

43

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

Page 44: 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.

44

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

Page 45: 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.

45

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

Page 46: 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.

46

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

Page 47: 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.

47

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

Page 48: 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.

48

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;

Page 49: 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.

49

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"; } }

Page 50: 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.

String

50

Page 51: 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.

51

StringConstructor.cs

using System; using System.Windows.Forms;

class StringConstructor {

static void Main( string[] args ) { string output; string originalString, string1, string2, string3, string4; char[] characterArray = {'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };

originalString = "Welcome to C# programming!"; string1 = originalString; string2 = new string( characterArray ); string3 = new string( characterArray, 6, 3 ); string4 = new string( 'C', 5 ); output = "string1 = " + "\"" + string1 + "\"\n" + "string2 = " + "\"" + string2 + "\"\n" + "string3 = " + "\"" + string3 + "\"\n" + "string4 = " + "\"" + string4 + "\"\n";

Page 52: 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.

String Indexer, Length Property and CopyTo Method

• String indexer

– Retrieval of any character in the string

• Length property

– Returns the length of the string

• CopyTo

– Copies specified number of characters into a char array

Page 53: 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.

53

StringMethods.cs

using System; using System.Windows.Forms; class StringMethods { static void Main( string[] args ) { string string1, output; char[] characterArray; string1 = "hello there"; characterArray = new char[ 5 ]; output = "string1: \"" + string1 + "\""; output += "\nLength of string1: " + string1.Length;

output += "\nThe string reversed is: "; for ( int i = string1.Length - 1; i >= 0; i-- ) output += string1[ i ];

Page 54: 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.

Comparing Strings

• String comparison

– Greater than

– Less than

• Method Equals

– Test objects for equality

– Return a Boolean

– Uses lexicographical comparison

Page 55: 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.

55

StringCompare.cs

using System; using System.Windows.Forms; class StringCompare { static void Main( string[] args ) { string string1 = "hello"; string string2 = "good bye"; string string3 = "Happy Birthday"; string string4 = "happy birthday"; string output; // output values of four strings output = "string1 = \"" + string1 + "\"" + "\nstring2 = \"" + string2 + "\"" + "\nstring3 = \"" + string3 + "\"" + "\nstring4 = \"" + string4 + "\"\n\n"; // test for equality using Equals method if ( string1.Equals( "hello" ) ) output += "string1 equals \"hello\"\n"; else output += "string1 does not equal \"hello\"\n"; // test for equality with == if ( string1 == "hello" ) output += "string1 equals \"hello\"\n";

Page 56: 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.

56

StringStartEnd.cs

using System; using System.Windows.Forms; class StringStartEnd { static void Main( string[] args ) { string[] strings = { "started", "starting", "ended", "ending" }; string output = ""; for ( int i = 0; i < strings.Length; i++ ) if ( strings[ i ].StartsWith( "st" ) ) output += "\"" + strings[ i ] + "\"" + " starts with \"st\"\n"; output += "\n"; // test every string to see if it ends with "ed“ for ( int i = 0; i < strings.Length; i ++ ) if ( strings[ i ].EndsWith( "ed" ) ) output += "\"" + strings[ i ] + "\"" + " ends with \"ed\"\n";

Page 57: 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.

Miscellaneous String Methods

• Method Replace – Original string remain unchanged

– Original string return if no occurrence matched

• Method ToUpper– Replace lower case letter

– Original string remain unchanged

– Original string return if no occurrence matched

• Method ToLower– Replace lower case letter

– Original string remain unchanged

– Original string return if no occurrence matched

Page 58: 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.

Miscellaneous String Methods

• Method ToString– Can be called to obtain a string representation of any object

• Method Trim– Remove whitespaces

– Remove characters in the array argument

Page 59: 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.

59

StringMiscellaneous2.cs

using System; using System.Windows.Forms; class StringMethods2 { static void Main( string[] args ) { string string1 = "cheers!"; string string2 = "GOOD BYE "; string string3 = " spaces "; string output; output = "string1 = \"" + string1 + "\"\n" + "string2 = \"" + string2 + "\"\n" + "string3 = \"" + string3 + "\""; // call method Replace output += "\n\nReplacing \"e\" with \"E\" in string1: \"" + string1.Replace( 'e', 'E' ) + "\""; // call ToLower and ToUpper output += "\n\nstring1.ToUpper() = \"" + string1.ToUpper() + "\"\nstring2.ToLower() = \"" + string2.ToLower() + "\"";

Page 60: 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.

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

Page 61: 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.

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

Page 62: 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.

• 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

Page 63: 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.

What will happen when you attempt to compile and run this code?

class Base{abstract public void myfunc();public void another(){console.writeline("Another method");}}

public class Abs : Base{public static void main(String argv[]){Abs a = new Abs();a.amethod();}

public void myfunc(){ console.writeline("My func");}

public void amethod(){myfunc();}}

Page 64: 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.

Data Abstraction and Information Hiding

• Classes should hide implementation details• Stacks

– Last-in, first-out (LIFO)

– Items are pushed onto the top of the stack

– Items are popped off the top of the stack

• Queues– Similar to a waiting line

– First-in, first-out (FIFO)

– Items are enqueued (added to the end)

– Items are dequeued (taken off the front)

Page 65: 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.

65

Derived-Class-Object to Base-Class-Object Conversion

• Class hierarchies

– Can assign derived-class objects to base-class

references

– Can explicitly cast between types in a class hierarchy

• An object of a derived-class can be treated as an object of

its base-class

– Array of base-class references that refer to objects of

many derived-class types

– Base-class object is NOT an object of any of its derived

classes

Page 66: 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.

66

using System; // Point class definition implicitly inherits from Object public class Point { // point coordinate private int x, y; // default constructor public Point() { // implicit call to Object constructor occurs here } public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here X = xValue; Y = yValue; } public int X { get { return x; }

Page 67: 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.

set { x = value; // no need for validation } } // end property X // property Y public int Y { get { return y; } set { y = value; // no need for validation } } // end property Y // return string representation of Point public override string ToString() { return "[" + X + ", " + Y + "]"; } } // end class Point

67

Page 68: 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.

68

using System; // Circle class definition inherits from Point public class Circle : Point { private double radius; // circle's radius // default constructor public Circle() { // implicit call to Point constructor occurs here } public Circle( int xValue, int yValue, double radiusValue ) : base( xValue, yValue ) { Radius = radiusValue; } // property Radius public double Radius { get { return radius; }

Page 69: 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.

69

set { if ( value >= 0 ) // validate radius radius = value; } } // end property Radius public double Diameter() { return Radius * 2; } public double Circumference() { return Math.PI * Diameter(); } public virtual double Area() { return Math.PI * Math.Pow( Radius, 2 ); } public override string ToString() { return "Center = " + base.ToString() + "; Radius = " + Radius; } } // end class Circle

Page 70: 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.

70

using System; using System.Windows.Forms;class PointCircleTest { // main entry point for application. static void Main( string[] args ) { Point point1 = new Point( 30, 50 ); Circle circle1 = new Circle( 120, 89, 2.7 );

string output = "Point point1: " + point1.ToString() + "\nCircle circle1: " + circle1.ToString(); // use 'is a' relationship to assign // Circle circle1 to Point reference Point point2 = circle1;output += "\n\nCCircle circle1 (via point2): " + point2.ToString(); // downcast (cast base-class reference to derived-class // data type) point2 to Circle circle2 Circle circle2 = ( Circle ) point2; output += "\n\nCircle circle1 (via circle2): " + circle2.ToString(); output += "\nArea of circle1 (via circle2): " + circle2.Area().ToString( "F" );

Page 71: 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.

71

// attempt to assign point1 object to Circle reference if ( point1 is Circle ) { circle2 = ( Circle ) point1; output += "\n\ncast successful"; } else { output += "\n\npoint1 does not refer to a Circle"; } MessageBox.Show( output, "Demonstrating the 'is a' relationship" ); } // end method Main } // end class PointCircleTest

Page 72: 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.

72

Interfaces

• Interfaces specify the public services (methods

and properties) that classes must implement

• Interfaces provide no default implementations vs.

abstract classes which may provide some default

implementations

• Interfaces are used to “bring together” or relate

disparate objects that relate to one another only

through the interface

Page 73: 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.

73

Interfaces

• Interfaces are defined using keyword interface• Use inheritance notation to specify a class

implements an interface (ClassName : InterfaceName)

• Classes may implement more than one interface (a comma separated list of interfaces)

• Classes that implement an interface, must provide implementations for every method and property in the interface definition

Page 74: 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.

74

public interface Ishape { // classes that implement IShape must implement these methods // and this property double Area(); double Volume(); string Name { get; } }

Page 75: 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.

75

// an x-y coordinate pair. using System; public class Point3 : Ishape { private int x, y; // Point3 coordinates public Point3() { } // constructor public Point3( int xValue, int yValue ) { X = xValue; Y = yValue; } // property X public int X { get { return x; }

Page 76: 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.

7632 set33 {34 x = value;35 }36 }37 39 public int Y40 {41 get42 {43 return y;44 }45 46 set47 {48 y = value;49 }50 }51 52 // return string representation of Point3 object53 public override string ToString()54 {55 return "[" + X + ", " + Y + "]";56 }57 58 // implement interface IShape method Area59 public virtual double Area()60 {61 return 0;62 }63

Page 77: 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.

77

64 // implement interface IShape method Volume65 public virtual double Volume()66 {67 return 0;68 }69 70 // implement property Name of IShape71 public virtual string Name72 {73 get74 {75 return "Point3";76 }77 }78 79 } // end class Point3

Implementation of IShape property Name (required), declared virtual to allow deriving classes to override

Page 78: 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.

78

3 using System;4 5 // Circle3 inherits from class Point36 public class Circle3 : Point37 {8 private double radius; // Circle3 radius9 10 // default constructor11 public Circle3()12 {13 // implicit call to Point3 constructor occurs here14 }15 16 // constructor17 public Circle3( int xValue, int yValue, double radiusValue )18 : base( xValue, yValue )19 {20 Radius = radiusValue;21 }22 23 // property Radius24 public double Radius25 {26 get27 {28 return radius;29 }30

Page 79: 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.

7931 set32 {33 // ensure non-negative Radius value34 if ( value >= 0 )35 radius = value;36 }37 }38 40 public double Diameter()41 {42 return Radius * 2;43 }44 45 // calculate Circle3 circumference46 public double Circumference()47 {48 return Math.PI * Diameter();49 }50 51 // calculate Circle3 area52 public override double Area()53 {54 return Math.PI * Math.Pow( Radius, 2 );55 }56 57 // return string representation of Circle3 object58 public override string ToString()59 {60 return "Center = " + base.ToString() +61 "; Radius = " + Radius;62 }63

Page 80: 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.

80

64 // override property Name from class Point365 public override string Name66 {67 get68 {69 return "Circle3";70 }71 }72 73 } // end class Circle3

Page 81: 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.

81

3 using System;5 // Cylinder3 inherits from class Circle36 public class Cylinder3 : Circle37 {8 private double height; // Cylinder3 height9 10 // default constructor11 public Cylinder3()12 {13 // implicit call to Circle3 constructor occurs here14 }15 16 // constructor17 public Cylinder3( int xValue, int yValue, double radiusValue,18 double heightValue ) : base( xValue, yValue, radiusValue )19 {20 Height = heightValue;21 }22 23 // property Height24 public double Height25 {26 get27 {28 return height;29 }30

Page 82: 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.

82

31 set32 {33 // ensure non-negative Height value34 if ( value >= 0 )35 height = value;36 }37 }38 39 // calculate Cylinder3 area40 public override double Area()41 {42 return 2 * base.Area() + base.Circumference() * Height;43 }44 45 // calculate Cylinder3 volume46 public override double Volume()47 {48 return base.Area() * Height;49 }50 51 // return string representation of Cylinder3 object52 public override string ToString()53 {54 return "Center = " + base.ToString() +55 "; Height = " + Height;56 }57

Page 83: 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.

83

58 // override property Name from class Circle359 public override string Name60 {61 get62 {63 return "Cylinder3";64 }65 }66 67 } // end class Cylinder3

Page 84: 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.

84

5 using System.Windows.Forms;6 7 public class Interfaces2Test8 {9 public static void Main( string[] args )10 {11 // instantiate Point3, Circle3 and Cylinder3 objects12 Point3 point = new Point3( 7, 11 );13 Circle3 circle = new Circle3( 22, 8, 3.5 );14 Cylinder3 cylinder = new Cylinder3( 10, 10, 3.3, 10 );15 16 // create array of IShape references17 IShape[] arrayOfShapes = new IShape[ 3 ];18 19 // arrayOfShapes[ 0 ] references Point3 object20 arrayOfShapes[ 0 ] = point;21 22 // arrayOfShapes[ 1 ] references Circle3 object23 arrayOfShapes[ 1 ] = circle;24 25 // arrayOfShapes[ 2 ] references Cylinder3 object26 arrayOfShapes[ 2 ] = cylinder;27 28 string output = point.Name + ": " + point + "\n" +29 circle.Name + ": " + circle + "\n" +30 cylinder.Name + ": " + cylinder;31

Page 85: 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.

32 foreach ( IShape shape in arrayOfShapes )33 {34 output += "\n\n" + shape.Name + ":\nArea = " + 35 shape.Area() + "\nVolume = " + shape.Volume();36 }37 38 MessageBox.Show( output, "Demonstrating Polymorphism" );39 }40 }