Introduction to Object-Oriented Programming and Inheritance in CS112, Slides of C programming

This document from the cs112 course at yale university explores the concept of object-oriented programming (oop) and inheritance in c#. It explains how classes serve as program modules and blueprints for generating objects, the role of inheritance in code reuse, and the meaning of 'is-a' relationships. The document also covers the use of protected visibility modifiers and calling a parent's constructor in a child's constructor.

Typology: Slides

2010/2011

Uploaded on 10/06/2011

christina
christina 🇺🇸

4.6

(23)

393 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS 112 Introduction to
Programming
Lecture #31:
OO Programming and Inheritance
http://flint.cs.yale.edu/cs112/
2
C# Classes
rC# classes play dual roles:
mprogram modules: contain a list of (static) method
declarations and (static) data fields
mblueprints for generating objects:
data and methods
rClasses support
m“data encapsulation” (e.g., private components, for
abstraction)
minheritance” (for code reuse)
3
Inheritance
rInheritance allows a software developer to derive a
new class from an existing one
rThe existing class is called the parent class, or
superclass, or base class
rThe derived class is called the child class, or
subclass, or derived class.
rAs the name implies, the child inherits characteristics
of the parent
rThat is, the child class inherits the methods and data
defined for the parent class
4
Inheritance
rInheritance 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
is-
-a
a
relationship
relationship,
,
meaning the child
meaning the child
is a
is a more specific
more specific
version of the
version of the
parent
parent
Animal
# weight : int
+ GetWeight() : int
Bird
+ Fly() : void
Animal
Bird
5
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.
6
Declaring a Derived Class
rDefine a new class DerivedClass which extends BaseClass
class BaseClass
{
// class contents
}
class DerivedClass : BaseClass
{
// class contents
}
rBase class: the “parent” class; if omitted the parent is Object
See Book.cs, Dictionary.cs, BookInheritance.cs
pf3
pf4
pf5

Partial preview of the text

Download Introduction to Object-Oriented Programming and Inheritance in CS112 and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #31:

OO Programming and Inheritance

http://flint.cs.yale.edu/cs112/

2

C# Classes

r C# classes play dual roles: m program modules: contain a list of (static) method declarations and (static) data fields m blueprints for generating objects:

  • data and methods

r Classes support m “data encapsulation” (e.g., private components, for abstraction) m “inheritance” (for code reuse)

3

Inheritance

r Inheritance allows a software developer to derive a new class from an existing one

r The existing class is called the parent class, or superclass , or base class

r The derived class is called the child class, or subclass, or derived class.

r As the name implies, the child inherits characteristics of the parent

r That is, the child class inherits the methods and data defined for the parent class 4

Inheritance

r Inheritance relationships are often shown

graphically in a class diagram , with the arrow

pointing to the parent class

Inheritance should Inheritance should create ancreate an isis--aa relationshiprelationship ,, meaning the childmeaning the child is ais a more specificmore specific version of theversion of the parentparent

Animal

weight : int

  • GetWeight() : int

Bird

  • Fly() : void

Animal

Bird

5

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.

6

Declaring a Derived Class

r Define a new class DerivedClass which extends BaseClass

class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents }

r Base class: the “parent” class; if omitted the parent is Object

See Book.cs, Dictionary.cs, BookInheritance.cs

7

Controlling Inheritance

r 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 r Variables and methods declared with private visibility are not accessible in the child class m a private data member defined in the parent class is still part of the state of a derived class r Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation r There is a third visibility modifier that helps in inheritance situations: protected

8

The protected Modifier

q 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

q The details of each modifier are linked on the schedule page

r Example m Book.cs m Dictionary.cs m TestBookDictionary.cs

Book # pages : int

  • GetNumberOfPages() : void

Dictionary

  • definition : int
  • public + PrintDefinitionMessage() : void
  • private

protected

9

Calling Parent’s Constructor in a Child’s

Constructor: the base Reference

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

rExample mSee FoodItem.cs mSee Pizza.cs mSee FoodAnalysis.cs (^10)

Defining Methods in the Child Class:

Overriding Methods

r A child class can override the definition of an

inherited method in favor of its own

r That is, a child can redefine a method that it

inherits from its parent

r The new method must have the same

signature as the parent's method, but can have

different code in the body

r The type of the object executing the method

determines which version of the method is

invoked

11

Overriding Methods: Syntax

r override keyword is needed if a derived-

class method overrides a base-class method

r If a base class method is going to be

overridden it should be declared virtual

rExample mThought.cs mAdvice.cs mThoughtAndAdvice.cs

12

Overloading vs. Overriding

r Overloading deals with multiple methods in the same class with the same name but different signatures

r Overloading lets you define a similar operation in different ways for different data

r Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

r Overriding lets you define a similar operation in different ways for different object types

19

References and Inheritance

r An object reference can refer to an object of its

class, or to an object of any class derived from

it by inheritance

r 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

20

References and Inheritance

r Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment

r 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

r The widening conversion is the most useful m for implementing polymorphism

Holiday day = new Christmas();

Christmas christ = new Christmas(); Holiday day = christ; Christmas christ2 = (Christmas)day;

21

Polymorphism via Inheritance

r A polymorphic reference is one which can refer to different types of objects at different times

r 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 m it is the type of the object being referenced, not the reference type, that determines which method is invoked m polymorphic references are therefore resolved at run-time, not during compilation; this is called dynamic binding

r Careful use of polymorphic references can lead to elegant, robust software designs

22

Polymorphism via Inheritance

r Suppose the Holiday class has a method

called Celebrate, and the Christmas class

redfines it

r Now consider the following invocation:

day.Celebrate();

r 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

23

Polymorphism via Inheritance: Example 1

r Consider how to model a collection of shapes

r Example

m Shape.cs m Circle.cs m Sphere.cs m Cylinder.cs

24

Polymorphism via Inheritance: Example 2

StaffMember

name : string

address : string

phone : string

  • ToString() : string + Pay() : double

Volunteer

+ Pay() : double

Employee

socialSecurityNumber : String

payRate : double

  • ToString() : string + Pay() : double

Executive

  • bonus : double
  • AwardBonus(execBonus : double) : void + Pay() : double

Hourly

  • hoursWorked : int
  • AddHours(moreHours : int) : void
  • ToString() : string + Pay() : double

25

Polymorphism via Inheritance and

Arrays of Objects

r Polymorphic references and arrays work well

with each other

r See

m StaffMember.cs m Volunteer.cs

m Employee.cs m Executive.cs m Hourly.cs m Staff.cs m PayRoll.cs