Programming Abstractions Cynthia Lee CS106X. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism › Example: Expression.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
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.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CS 211 Inheritance AAA.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
. Virtual Classes & Polymorphism. Example (revisited) u We want to implement a graphics system u We plan to have lists of shape. Each shape should be.
Inheritance Chapter 8.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
DERIVED CLASSES AND INHERITANCE Moshe Fresko Bar-Ilan University Object Oriented Programing
Inheritance and Polymorphism CS351 – Programming Paradigms.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Polymorphism &Virtual Functions
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Lecture 21 Multiple Inheritance. What is Multiple Inheritance? We defined inheritance earlier in the semester as a relationship between classes. If class.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Programming Abstractions Cynthia Lee CS106X. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism › Example: Expression.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
Interfaces Chapter 9. 9 Creating Interfaces An interface is a contract. Every class that implements the interface must provide the interface’s defined.
CSE 143 Lecture 12 Inheritance slides created by Ethan Apter
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
© 2007 Lawrenceville Press Slide 1 Chapter 9 Inheritance  One class is an extension of another.  Allows a class to define a specialized type of an existing.
Overview of C++ Polymorphism
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
Inheritance ndex.html ndex.htmland “Java.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
CPSC 252Inheritance II Page 1 Inheritance & Pointers Consider the following client code: const int MAXCLOCKS = 2; Clock* clockPtr[ MAXCLOCKS ]; clockPtr[0]
BY:- TOPS Technologies
Programming Abstractions Cynthia Lee CS106B. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-3: Polymorphism reading: 9.3.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
CSE 143 Lecture 13 Inheritance slides created by Ethan Apter
Building Java Programs
Programming Abstractions
Inheritance Based on slides by Ethan Apter
7. Inheritance and Polymorphism
Expression Trees Eric Roberts CS 106B March 4, 2013.
Lecture 17: Polymorphism (Part II)
Building Java Programs
One class is an extension of another.
More inheritance, Abstract Classes and Interfaces
Virtual Functions Department of CSE, BUET Chapter 10.
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Advanced Programming in Java
Lecture 18: Polymorphism (Part II)
Abstract Classes and Interfaces
Overview of C++ Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Building Java Programs
Programming Abstractions in C++, Chapter 19
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Presentation transcript:

Programming Abstractions Cynthia Lee CS106X

Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism › Example: Expression trees (final project)

Polymorphism Start with how

Polymorphism polymorphism: Ability for the same code to be used with different types of objects and behave differently with each.  Templates provide a kind of compile-time polymorphism. › Grid or Grid will output different things for myGrid[0][0], but we can predict at compile time which it will do  Inheritance provides run-time polymorphism. › someEmployee.salary() will behave differently at runtime depending on what type of employee—may not be able to predict at compile time which it is

Polymorphism We will keep working with the Employee class: 5  Employees have a name, years worked, salary, vacation, …  Lawyers know how to sue and get paid 2x as much  Programmers know how to write code and get bigger raises each year  (Code is now on lectures page of website.)

Polymorphism A pointer of type T can point to any subclass of T. Employee *neha = new Programmer("Neha", 2); Employee *diane = new Lawyer("Diane", "Stanford", 5); Programmer *cynthia = new Programmer("Cynthia", 10);  Why would you do this? › Handy if you want to have a function that works on any Employee, but takes advantage of custom behavior by specific employee type: void doMonthlyPaycheck(Employee *employee) { cout salary()/12 << " wealthier!" << endl; }

Polymorphism A pointer of type T can point to any subclass of T. Employee *neha = new Programmer("Neha", 2); Employee *diane = new Lawyer("Diane", "Stanford", 5); Programmer *cynthia = new Programmer("Cynthia", 10);  When a member function is called on diane, it behaves as a Lawyer. › diane->salary(); › (This is because all the employee functions are declared virtual.)  You can not call any Lawyer -only members on diane (e.g. sue ). › diane->sue(); // will NOT compile!  You can call any Programmer -only members on cynthia (e.g. code ). › cynthia->code("Java"); // ok!

Polymorphism examples You can use the object's extra functionality by casting. Employee *diane = new Lawyer("Diane", "Stanford", 5); diane->vacationDays(); // ok diane->sue("Cynthia"); // compiler error ((Lawyer*) diane)->sue("Cynthia"); // ok Pro Tip: you should not cast a pointer into something that it is not! It will compile, but the code will crash (or behave unpredictably) when you try to run it. Employee *carlos = new Programmer("Carlos", 3); carlos->code(); // compiler error ((Programmer*) carlos)->code("C++"); // ok ((Lawyer*) carlos)->sue("Cynthia"); // No!!! Compiles but crash!!

Rules for “virtual”: runtime calls DerivedType * obj = new DerivedType(); If we call a method like this: obj->method(), only one thing could happen: 1.DerivedType’s implementation of method is called BaseType * obj = new DerivedType(); If we call a method like this: obj->method(), two different things could happen: 1.If method is not virtual, then BaseType’s implementation of method is called 2.If method is virtual, then DerivedType’s implementation of method is called

Rules for “virtual”: pure virtual If a method of a class looks like this:  virtual returntype method() = 0;  then this method is a called “pure virtual” function  and the class is called an “abstract class”  Abstract classes are like Java interfaces  You cannot do “= new Foo();” if Foo is abstract (just like Java interfaces)  ALSO, you cannot do “= new DerivedFoo();” if DerivedFoo extends Foo and DerivedFoo does not implement all the pure virtual methods of Foo

class Mammal { public: virtual void makeSound() = 0; string toString() { return “Mammal”; } }; class Cat : public Mammal { public: virtual void makeSound() { cout << “rawr” << endl; } string toString() { return “Cat”; } }; class Siamese : public Cat { public: virtual void makeSound() { cout << “meow” << endl; } string toString() { return “Siamese”; } virtual void scratchCouch() { cout << “scraaaatch” << endl; } }; What is printed? S iamese * s = new Mammal; cout toString(); (A)“Mammal” (B)“Cat” (C)“Siamese” (D) Gives an error (identify compiler or crash) (E) Other/none/more

class Mammal { public: virtual void makeSound() = 0; string toString() { return “Mammal”; } }; class Cat : public Mammal { public: virtual void makeSound() { cout << “rawr” << endl; } string toString() { return “Cat”; } }; class Siamese : public Cat { public: virtual void makeSound() { cout << “meow” << endl; } string toString() { return “Siamese”; } virtual void scratchCouch() { cout << “scraaaatch” << endl; } }; What is printed? S iamese * s = new Siamese; cout toString(); (A)“Mammal” (B)“Cat” (C)“Siamese” (D) Gives an error (identify compiler or crash) (E) Other/none/more

class Mammal { public: virtual void makeSound() = 0; string toString() { return “Mammal”; } }; class Cat : public Mammal { public: virtual void makeSound() { cout << “rawr” << endl; } string toString() { return “Cat”; } }; class Siamese : public Cat { public: virtual void makeSound() { cout << “meow” << endl; } string toString() { return “Siamese”; } virtual void scratchCouch() { cout << “scraaaatch” << endl; } }; What is printed? Mammal * m = new Mammal; cout toString(); (A)“Mammal” (B)“Cat” (C)“Siamese” (D) Gives an error (identify compiler or crash) (E) Other/none/more

class Mammal { public: virtual void makeSound() = 0; string toString() { return “Mammal”; } }; class Cat : public Mammal { public: virtual void makeSound() { cout << “rawr” << endl; } string toString() { return “Cat”; } }; class Siamese : public Cat { public: virtual void makeSound() { cout << “meow” << endl; } string toString() { return “Siamese”; } virtual void scratchCouch() { cout << “scraaaatch” << endl; } }; What is printed? Mammal * m = new Siamese; cout toString(); (A)“Mammal” (B)“Cat” (C)“Siamese” (D) Gives an error (identify compiler or crash) (E) Other/none/more

class Mammal { public: virtual void makeSound() = 0; string toString() { return “Mammal”; } }; class Cat : public Mammal { public: virtual void makeSound() { cout << “rawr” << endl; } string toString() { return “Cat”; } }; class Siamese : public Cat { public: virtual void makeSound() { cout << “meow” << endl; } string toString() { return “Siamese”; } virtual void scratchCouch() { cout << “scraaaatch” << endl; } }; What is printed? Mammal * m = new Siamese; m->scratchCouch(); (A)“Mammal” (B)“Cat” (C)“Siamese” (D) Gives an error (identify compiler or crash) (E) Other/none/more

class Mammal { public: virtual void makeSound() = 0; string toString() { return “Mammal”; } }; class Cat : public Mammal { public: virtual void makeSound() { cout << “rawr” << endl; } string toString() { return “Cat”; } }; class Siamese : public Cat { public: virtual void makeSound() { cout << “meow” << endl; } string toString() { return “Siamese”; } virtual void scratchCouch() { cout << “scraaaatch” << endl; } }; What is printed? Cat * c = new Siamese; c->makeSound(); (A)“rawr” (B)“meow” (C)“Siamese” (D) Gives an error (identify compiler or crash) (E) Other/none/more

Stanford Walkthrough The Expression class

Walkthrough of Stanford  Excel-like spreadsheet  Among other things, it needs to parse expressions › = (3 + 4) * A7  We saw something similar to this earlier in the quarter: * +/ 3428

Evaluation of CompoundExp This is in the implementation of CompoundExp —let’s take a look at the.h file to see what op, lhs, and rhs are

C++ and the “virtual” keyword

Expression (base class) Note: you cannot actually create an Expression object These methods are never implemented (note the “ = 0 ”)  “pure virtual” Expression exists solely to provide a base class to others  “abstract”

Another Derived class: DoubleExp

Another Derived class: IdentifierExp

This diagram shows a CompoundExp object as the root of a tree, and the children are the LHS and RHS (private member variables of type Expressio*). LHS points to an object of type DoubleExp, with value 3.7. RHS points to an object of type IdentifierExp with name “foo”. Note that it is ok for the RHS and LHS pointers to point to DoubleExp and IdentifierExp objects, because these are derived classes of the base class Expression. Stanford eval Because of the “is a” relationship: lhs/rhs of compoundExp can be any of:  CompoundExp  DoubleExp  IdentifierExp

This diagram shows a CompoundExp object as the root of a tree, and the children are the LHS and RHS (private member variables of type Expressio*). LHS points to an object of type DoubleExp, with value 3.7. RHS points to an object of type IdentifierExp with name “foo”. Note that it is ok for the RHS and LHS pointers to point to DoubleExp and IdentifierExp objects, because these are derived classes of the base class Expression. Stanford eval CompoundExp doesn’t want to care exactly what type its lhs and rhs are Just calls eval() on whatever they are and gets the right value!