Programming in C# Inheritance and Polymorphism

Similar documents
Inheritance -- Introduction

Inheritance Motivation

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

Inheritance and Polymorphism

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Inheritance (Deitel chapter 9)

Java Object Oriented Design. CSC207 Fall 2014

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Problem: Given a vector of pointers to Shape objects, print the area of each of the shape.

Chapter 6 Reflection

Polymorphism. Polymorphism is an object-oriented concept that allows us to create versatile software designs

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Inheritance and Polymorphism

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Object Oriented Programming

CS-202 Introduction to Object Oriented Programming

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Polymorphism. Agenda

CS111: PROGRAMMING LANGUAGE II

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

ITI Introduction to Computing II

Object Oriented Programming. Java-Lecture 11 Polymorphism

A A B U n i v e r s i t y

Chapter 9 - Object-Oriented Programming: Inheritance

ITI Introduction to Computing II

CS 112 Introduction to Programming

Admin. q Admin and recap q Class inheritance

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Introduction to inheritance

Lecture 18 CSE11 Fall 2013 Inheritance

ECE 122. Engineering Problem Solving with Java

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Inheritance Introduction. 9.1 Introduction 361

Computer Science II (20073) Week 1: Review and Inheritance

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Inheritance and Polymorphism

8. Polymorphism and Inheritance

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

OVERRIDING. 7/11/2015 Budditha Hettige 82

Chapter 5 Object-Oriented Programming

Inheritance, Polymorphism, and Interfaces

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Classes and Inheritance Extending Classes, Chapter 5.2

ECE 3574: Dynamic Polymorphism using Inheritance

Data Structures and Other Objects Using C++

Comp 249 Programming Methodology

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exercise: Singleton 1

CHAPTER 6 Class-Advanced Concepts - Inheritance

9/10/2018 Programming Data Structures Inheritance

Inheritance. Chapter 7. Chapter 7 1

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

More Relationships Between Classes

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Polymorphism and Inheritance

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Building custom components IAT351

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

CS111: PROGRAMMING LANGUAGE II

Inheritance and object compatibility

Binghamton University. CS-140 Fall Dynamic Types

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

What is Inheritance?

Data Structures (list, dictionary, tuples, sets, strings)

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More On inheritance. What you can do in subclass regarding methods:

Inheritance and Encapsulation. Amit Gupta

Programming II (CS300)

Lecture 5: Inheritance

Chapter 14 Abstract Classes and Interfaces

Inheritance. Transitivity

Inheritance and Polymorphism

What are the characteristics of Object Oriented programming language?

CIS 110: Introduction to computer programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

CS 112 Introduction to Programming. (Spring 2012)

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Inheritance & Polymorphism

CLASS DESIGN. Objectives MODULE 4

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Data Abstraction. Hwansoo Han

Polymorphism Part 1 1

PROGRAMMING LANGUAGE 2

Overriding Variables: Shadowing

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Transcription:

Programming in C# Inheritance and Polymorphism

C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data and method signatures Classes support Data encapsulation - private data and implementation. Inheritance - code reuse

Inheritance Inheritance allows a software developer to derive a new class from an existing one. The existing class is called the parent, super, or base class. The derived class is called a child or subclass. The child inherits characteristics of the parent. Methods and data defined for the parent class. The child has special rights to the parents methods and data. Public access like any one else Protected access available only to child classes (and their descendants). The child has its own unique behaviors and data.

Inheritance Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class. Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent. Animal Bird

Examples: Base Classes and Derived Classes Ba se c la ss Student Shape Loan Employee Account Derived c la sses GraduateStudent UndergraduateStudent Circle Triangle Rectangle CarLoan HomeImprovementLoan MortgageLoan FacultyMember StaffMember CheckingAccount SavingsAccount

Declaring a Derived Class Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents }

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 However, 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.

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 # pages : int Book + GetNumberOfPages() : void Dictionary - definition : int + PrintDefinitionMessage() : void + public - private # protected

Single 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. C# and Java support single inheritance, meaning that a derived class can have only one parent 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 a different implementation. The type of the object executing the method determines which version of the method is invoked.

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 Parrot Horse Bat

Class Hierarchies CommunityMember Employee Student Alumnus Faculty Staff Under Graduate Professor Instructor

Class Hierarchies Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Cylinder

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. Avoids redundant code.

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

Dynamic Binding A polymorphic reference is one which can refer to different types of objects at different times. It morphs! The type of the actual instance, not the declared type, determines which method is invoked. Polymorphic references are therefore resolved at run-time, not during compilation. This is called dynamic binding.

Dynamic Binding Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides 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

Overriding Methods C# requires that all class definitions communicate clearly their intentions. The keywords virtual, override and new provide this communication. If a base class method is going to be overridden it should be declared virtual. A derived class would then indicate that it indeed does override the method with the override keyword.

Overriding Methods If a derived class wishes to hide a method in the parent class, it will use the new keyword. This should be avoided.

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 Example: int foo(string[] bar); int foo(int bar1, float a); 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 Example: class Base { public virtual int foo() {} } class Derived { public override int foo() {}}

Polymorphism via Inheritance StaffMember # name : string # address : string # phone : string + ToString() : string + Pay() : double Volunteer + Pay() : double Employee # socialsecuritynumber : String # payrate : double + ToString() : string + Pay() : double - bonus : double Executive + AwardBonus(execBonus : double) : void + Pay() : double Hourly - hoursworked : int + AddHours(moreHours : int) : void + ToString() : string + Pay() : double

Widening and Narrowing Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment Holiday day = new Christmas(); 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: Christmas christ = new Christmas(); Holiday day = christ; Christmas christ2 = (Christmas)day;

Widening and Narrowing Widening conversions are most common. Used in polymorphism. Note: Do not be confused with the term widening or narrowing and memory. Many books use shor to long as a widening conversion. A long just happens to take-up more memory in this case. More accurately, think in terms of sets: The set of animals is greater than the set of parrots. The set of whole numbers between 0-65535 (ushort) is greater (wider) than those from 0-255 (byte).

Type Unification Everything in C# inherits from object Similar to Java except includes value types. Value types are still light-weight and handled specially by the CLI/CLR. This provides a single base type for all instances of all types. Called Type Unification

The System.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 a direct descendant 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