Inheritance Version 1.0. Topics Inheritance Constructors and Inheritance Hiding Methods and Variables Designing with Inheritance.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

OOP: Inheritance By: Lamiaa Said.
Inheritance. Topics Inheritance Constructors and Inheritance Overriding Functions and Variables Designing with Inheritance.
Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 211 Inheritance AAA.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Polymorphism, Virtual Methods and Abstract Classes.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Computer Science I Inheritance Professor Evan Korth New York University.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Inheritance Version 1.1. Topics Inheritance Constructors and Inheritance Function Over-riding (Redefinition) The Stringstream class Shadowing Variables.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Topic 4 Inheritance.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance Notes Chapter 6 1. Inheritance  you know a lot about an object by knowing its class  for example what is a Komondor? 2
Copyright © Curt Hill Inheritance in C++ How to do it.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Reusing Classes composition The trick is to use the classes without soiling the existing code. In this chapter you’ll see two ways to accomplish.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Polymorphism, Virtual Methods and Interfaces Version 1.1.
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
SUBCLASSES - JAVA. The Purpose of Subclasses Class Farm String getOwner() void setOwner(String s) int getSize() void setSize(int s) Class DairyFarm String.
Polymorphism, Virtual Methods and Abstract Classes
Inheritance and Polymorphism
Road Map Inheritance Class hierarchy Overriding methods Constructors
Polymorphism, Virtual Methods and Abstract Classes
ATS Application Programming: Java Programming
Inheritance.
Inheritance Basics Programming with Inheritance
Computer Programming with JAVA
Presentation transcript:

Inheritance Version 1.0

Topics Inheritance Constructors and Inheritance Hiding Methods and Variables Designing with Inheritance

Objectives After completing this topic, students should be able to: Correctly design and use classes that use inheritance in a C# program * Know how to correctly call the parent constructor * know how to hide methods and data in the parent class * Know when to use the protected attribute

Inheritance is the act of deriving a new class from an already existing class. It is analogous to creating a new house blueprint from an existing one. Inheritance is useful when we find a natural hierarchical relationship between classes. Inheritance makes it possible to re-use existing code, thus saving time and minimizing bugs.

Example and Terminology

Suppose that we are creating a new role playing game, and we want to have the following creatures: dwarveselvesfairies

All of these are “creatures “. They all have A name A strength value A hitpoint value dwarveselvesfairies

We could define a class for each such as: public class Dwarf { private string name; private int strength; private int hitpoints; //other dwarf data public Dwarf( ); public GetDamage( ); // other dwarf methods } public class Elf { private string name; private int strength; private int hitpoints; //other elf data public Elf( ); public GetDamage( ); // other elf methods } public class Fairy { private string name; private int strength; private int hitpoints; //other fairy data public Fairy( ); public GetDamage( ); // other fairy methods }

public class Dwarf { private string name; private int strength; private int hitpoints; //other dwarf data public Dwarf( ); public GetDamage( ); // other dwarf methods } public class Elf { private string name; private int strength; private int hitpoints; //other elf data public Elf( ); public GetDamage( ); // other elf methods } public class Fairy { private string name; private int strength; private int hitpoints; //other fairy data public Fairy( ); public GetDamage( ); // other fairy methods } Note that all of these classes have some things in common

public class Dwarf { private string name; private int strength; private int hitpoints; //other dwarf data public Dwarf( ); public GetDamage( ); // other dwarf methods } public class Elf { private string name; private int strength; private int hitpoints; //other elf data public Elf( ); public GetDamage( ); // other elf methods } public class Fairy { private string name; private int strength; private int hitpoints; //other fairy data public Fairy( ); public GetDamage( ); // other fairy methods } And They Have Some Things That Are Different

We gain a lot of productivity and functionality if we factor the common elements out into a base class. Creature name strength hitpoints DwarfElfFairy Base class Derived Class Sometimes also called parent class super class Sometimes also called child class sub class This relationship is called Inheritance.

If elves and fairies are both magical creatures, we might envision another layer of base and derived class Creature name strength hitpoints Dwarf Base class Derived Class Magical Creature spells ElfFairy Derived Class

This is known as a class hierarchy Creature name strength hitpoints Dwarf Magical Creature spells ElfFairy Dwarf inherits from Creature Elf and Fairy inherit from Magical Creature Magical Creature inherits from Creature

This is known as a class hierarchy Creature name strength hitpoints Dwarf Magical Creature spells ElfFairy Common things are defined in base classes Unique things are defined in derived classes

the protected modifier (#) tells us that the variable is accessible from within the Creature class and from within any derived classes. That is, methods of the derived class can see the protected data members defined in the base class. Creature name strength hitpoints Let’s look at the base class definition public class Creature { protected string name; protected int strength; protected int hitpoints; public Creature( ) { …}; public int getDamage( ) {…};... }

Creature name strength hitpoints And the MagicalCreature class public class MagicalCreature : Creature { protected int spells; public MagicalCreature( ) {…};... } The : means that this class inherits from the Creature class. That is, a MagicalCreature object will have everything that a Creature object has plus anything uniquely defined in The Magical Creature class. Magical Creature spells

So... If I create a MagicalCreature object named Zor, then Zor has the following properties: A name strength hitpoints spells - This comes from the MagicalCreature class These come from the Creature class

When data is declared as protected in a parent class, methods in a child class can see this data Protected Creature data MagicalSpell method

But be careful … methods in the parent class cannot see any data fields in the child part of the object. Creature method MagicalCreature data

This kind of inheritance is known as an is-a relationship. That is, a MagicalCreature is a Creature. An object of the MagicalCreature class can be used anyplace that an object of the Creature class can be used.

Let’s look at how we deal with differences between classes by Looking at the GetDamage( ) method. Dwarf ElfFairy GetDamage( ) computes and returns the damage that this creature inflicts in one round of combat. Every creature inflicts damage that is a random number between 1 and the creature’s strength value.

Dwarves are good fighters, and have a 25% chance of inflicting an additional 50 damage points Magical creatures can double the damage points if they have a magic spell. Fairies are very quick, so they can attack twice.

Creature name strength hitpoints Since the damage that any creature can inflict is defined as a random number between 0 and the creature’s strength value, we could write the following code in the base Creature class: public int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); return damage; }

Creature name strength hitpoints But if we create a Dwarf object “dw1”, and invoke the GetDamage method, this method will be executed, because a Dwarf is-a Creature. public int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); return damage; } Dwarf

Creature name strength hitpoints But …Dwarves have a 25% chance of inflicting an additional 50 damage points. So the GetDamage( ) method in the Dwarf class should look something like this: public int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); if (rgen.Next(1, 101) < 25) damage = damage + 50; return damage; } Dwarf

Creature name strength hitpoints Dwarf Now both the Creature class and the Dwarf class have a method named GetDamage( ). If we have a Dwarf object “dw1”, how do we get the compiler to use the GetDamage method in the Dwarf class? public int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); return damage; } public int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); if (rgen.Next(1, 101) < 25) damage = damage + 50; return damage; }

We hide, a method in the base class by writing a similar method in the derived class that has exactly the same signature, but with a different implementation. Then use the keyword new in the derived class method to tell the compiler to use this method on a derived object instead of the method of the same name in the base class. Hiding a Method in the Base Class

Creature name strength hitpoints Dwarf To Tell C# That We Want to hide the GetDamage Method in the base class public int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); return damage; } public new int GetDamage( ) { Random rgen = new Random( ); int damage = rgen.Next(0, strength + 1); if (rgen.Next(1, 101) < 25) damage = damage + 50; return damage; } tell the compiler that this method over-rides the GetDamage method in the base class by using the keyword new.

dw1 So, if I create a Dwarf object named dw1, and send dw1 a GetDamage( ) message... dw1.GetDamage( ) The GetDamage( ) method in the Dwarf class hides the GetDamage( ) method in the base class, and so the GetDamage( ) method in the Dwarf class gets executed.

dwarf Let’s let dwarves have a unique property of size. The class definition then might be: public class Dwarf : Creature { private int size; public Dwarf( ); public Dwarf(string, int, int, int); public int GetDamage( );... }

Now create a Dwarf object … Dwarf dw1 = new Dwarf( “Rohan”, 350, 500, 25); dw1 name strength hitPoints When the constructor is called, the computer looks at the Dwarf class to see how much storage to allocate. It notes that a Dwarf is a Creature, so it looks at the Creature class also. Enough storage is allocated for the data members of both the base and the derived classes. size Creature Part Dwarf Part

Dwarf::Dwarf (string _nme, int _strngth, int _hpts, int _sze) : base (_nme, _strngth, _hpts) { size = _sze; } The Dwarf Constructor Constructors are not inherited. In order to initialize the parent class we must invoke the base class constructor. If you do not explicitly call the Creature constructor, the default Creature constructor is called automatically. The base class constructor finishes executing before the derived class constructor does.

Hiding Variables If a derived class declares a variable using the same name as a variable in a parent class, the variable in the child class is said to hide the variable in the parent. You have to use the new keyword in the derived class.

Inheritance and References Because of the is-a relationship, an object of a derived class can always be treated as an object of the corresponding base class. In particular, you can always store the reference to a derived class object in a base class reference (upcast).

Dwarf littleDwarf = new Dwarf(“Egrew”, 600, 500, 2); Creature littleCreature; littleCreature = littleDwarf; littleDwarf littleCreature littleDwarf is A Dwarf object. littleCreature is a Creature reference

Dwarf littleDwarf = new Dwarf(“Egrew”, 600, 500, 2); Creature littleCreature; littleCreature = littleDwarf; Console.WriteLine(littleCreature.Size); littleDwarf littleCreature littleDwarf is A Dwarf object. littleCreature is a Creature reference Because littleCreature is a Creature reference you cannot directly access Dwarf data.

You can store the reference to a base class object in a derived class reference, but you must do an explicit cast to make this work. Dwarf littleDwarf; Creature anyOne = new Creature(“joe”, 400, 190); littleDwarf = (Dwarf)anyOne;

This is pretty dangerous and not often used, because the derived class reference thinks it is referencing a derived class object, but it really isn’t. This is referred to as the “slicing problem”. joe littleDwarf base part there is no derived part. If you try to access member data in the derived part, you will get garbage!

Upcasting vs. Downcasting Casting from a descendant type to an ancestor type is known as upcasting. It is always safe, since you are moving up the inheritance hierarchy. In our case, for example, we are always know that a dwarf is an creature. Casting from an ancestor type to a descendant type is called downcasting. In our case, we can’t guarantee that every creature is a dwarf, so downcasting a creature to a dwarf can be very dangerous, since we assume that information may be there that isn’t.

Designing With Inheritance

Usually we start with a notion of some very specific classes (Fairy, Elf, Dwarf … ) and move to more general classes by factoring out common data and operations.

Designing With Inheritance For example, suppose that we wanted to write a program that deals with instruments in an orchestra Violin Oboe Viola Clarinet Kettle Drum...

Designing With Inheritance Now design a class that contains all of the things that orchestra instruments have in common. * Instrument name * Owner * Where it is in the orchestra Then write methods to manage this data

Designing With Inheritance Look at all of the instruments in the orchestra. can they be organized into some different groups where each group has some things in common. Instrument WoodwindsBrassPercussionString

Violin Cello Instrument WoodwindsBrassPercussionString Kettle Drum Cymbals French Horn Trumpet Clarinet Oboe