visula c# programming lecture 7
DESCRIPTION
Lecture 7TRANSCRIPT
Visual Programming
OO Programming and Inheritance
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
Inheritance
Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class
Inheritance should Inheritance should create an create an is-a is-a relationshiprelationship, ,
meaning the child meaning the child is ais a more specific more specific
version of the version of the parentparent
Animal# weight : int
+ GetWeight() : int
Bird
+ Fly() : void
Animal
Bird
4
Examples: 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.
5
Declaring a Derived Class
Define a new class DerivedClass which extends BaseClass
class BaseClass
{
// class contents
}
class DerivedClass : BaseClass
{
// class contents
}
Base class: the “parent” class; if omitted the parent is Object
See Book.cs, Dictionary.cs, BookInheritance.cs
6
Controlling Inheritance
A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member
Variables and methods declared with private visibility are not accessible in the child class a private data member defined in the parent class is
still part of the state of a derived class Variables and methods declared with public
visibility are accessible; but public variables violate our goal of encapsulation
There is a third visibility modifier that helps in inheritance situations: protected
7
The protected Modifier
Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class
The details of each modifier are linked on the schedule page
Example Book.cs Dictionary.cs BookInheritance.cs
Book# pages : int
+ GetNumberOfPages() : void
Dictionary- definition : int
+ PrintDefinitionMessage() : void+ public- private# protected
8
Book.cs
using System; namespace BookInheritance {
/// <summary> /// Summary description for Book. /// </summary>
public class Book { protected int pages;
//---------------------------------------------------------------- // Constructors //----------------------------------------------------------------
public Book() { pages = 1500; } public Book( int pages ) { this.pages =
pages; }
//---------------------------------------------------------------- // Get the number of pages of this book. //----------------------------------------------------------------
public int GetNumberOfPages ()
{ return pages; } public void
PrintNumberOfPages () { Console.WriteLine ("Number of
pages is: " + pages); } } // end of class Book } // end of namespace
9
Dictionary.cs
using System;
namespace BookInheritance {
/// <summary> /// Summary description for Dictionary. /// </summary>
public class Dictionary : Book { private int definitions; //
number of definitions public Dictionary() { definitions =
52500; } public Dictionary(int
definitions) { this.definitions =
definitions; }
//-----------------------------------------------------------------// Prints a message using both local and inherited values.//-----------------------------------------------------------------public void PrintDefinitionMessage (){
Console.WriteLine ( "Number of definitions: " + definitions );Console.WriteLine ( "Average definitions per page: " + definitions / pages );
} // end of PrintDefinitionMessages} // end of class Dictionary
} // end of namespace
10
Book.cs
using System; namespace BookInheritance{ class BookInheritance { //----------------------------------------------------------------- // Instantiates a derived class and invokes its inherited and // local methods. //----------------------------------------------------------------- public static void Main (String[] args) { Dictionary webster = new Dictionary ();
int pages = webster.GetNumberOfPages();
// Console.WriteLine( webster.pages );
Console.WriteLine( "Number of pages is " + pages );
webster.PrintDefinitionMessage(); } } // end of class BookInheritance } // end of namespace
11
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 basepublic DerivedClass : BaseClass{ public DerivedClass(…) : base(…) { // … }}
12
Defining Methods in the Child Class: Overriding Methods
A child class can override the definition of an inherited method in favor of its own
That is, a child can redefine a method that it inherits from its parent
The new method must have the same signature as the parent's method, but can have different code in the body
The type of the object executing the method determines which version of the method is invoked
13
Overriding Methods: Syntax
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 should be declared virtual
ExampleThought.csAdvice.csThoughtAndAdvice.cs
14
Thought.cs using System; using System.Collections.Generic; using System.Text;
namespace ConsoleApplication3 { class Thought { //---------------------------------------------------- // Prints a message. //---------------------------------------------------- public virtual void Message() { Console.WriteLine("I feel like I'm in space ");
Console.WriteLine(); } // end of message
} }
15
Advice.cs using System; using System.Collections.Generic; using System.Text;
namespace ConsoleApplication3 { class Advice:Thought { //--------------------------------------------------------------- // Prints a message. This method overrides the parent's version. // It also invokes the parent's version explicitly using super. //----------------------------------------------------------------- public override void Message() { Console.WriteLine("Yor are on earth");
Console.WriteLine();
base.Message(); } // end of message
} }
16
ThoughtandAdvice.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication3{ class Program { //----------------------------------------------------------------- // Instatiates two objects a invokes the message method in each. //----------------------------------------------------------------- static void Main( string[] args ) { Thought t = new Thought(); Advice a = new Advice();
Console.WriteLine( "parked speak: "); t.Message();
Console.WriteLine( "dates speak: "); a.Message(); Console.ReadLine(); }}}
17
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
18
Single vs. Multiple Inheritance Some languages, e.g., C++, allow
Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents collisions, such as the same variable name in
two parents, are hard to resolve
Thus, C# and Java support single inheritance, meaning that a derived class can have only one parent class
19
Class Hierarchies
A child class of one parent can be the parent of another child, forming a class hierarchy
Animal
Reptile Bird Mammal
Snake Lizard BatHorseParrot
20
Another Example: Base Classes and Derived Classes
Fig. 9.2 Inheritance hierarchy for university CommunityMember.
CommunityMemeber
Employee Student Alumnus
Faculty Staff
Professor Instructor
GraduateUnder
21
Yet Another Example
Fig. 9.3 Portion of a Shape class hierarchy.
Shape
TwoDimensionalShape ThreeDimensionalShape
Sphere Cube CylinderTriangleSquareCircle
22
Class Hierarchies
An inherited member is continually passed down the line—inheritance is transitive
Good class design puts all common features as high in the hierarchy as is reasonable
23
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
See Student.cs GradStudent.cs and Academia.cs
24
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
25
References and Inheritance Assigning an object to an ancestor reference is
considered to be a widening conversion, and can be performed by simple assignment
Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast
The widening conversion is the most useful for implementing polymorphism
Holiday day = new Christmas();
Christmas christ = new Christmas();Holiday day = christ;Christmas christ2 = (Christmas)day;
26
Polymorphism via Inheritance
A polymorphic reference is one which can refer to different types of objects at different times
An object reference can refer to one object at one time, then it can be changed to refer to another object (related by inheritance) at another time it is the type of the object being referenced, not the
reference type, that determines which method is invoked
polymorphic references are therefore resolved at run-time, not during compilation; this is called dynamic binding
Careful use of polymorphic references can lead to elegant, robust software designs
27
Polymorphism via Inheritance
Suppose the Holiday class has a method called Celebrate, and the Christmas class redfines it
Now consider the following invocation:day.Celebrate();
If day refers to a Holiday object, it invokes the Holiday version of Celebrate; if it refers to a Christmas object, it invokes the Christmas version