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

Slides:



Advertisements
Similar presentations
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Advertisements

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.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Inheritance Readings: Writing classes Write an Employee class with methods that return values for the following properties of employees at a.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Copyright 2010 by Pearson Education Topic 31 - inheritance.
CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
CSC 142 Computer Science II Zhen Jiang West Chester University
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 14.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 19: encapsulation, inheritance reading: (Slides adapted from Stuart.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
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.,
Peyman Dodangeh Sharif University of Technology Fall 2014.
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Inheritance and Access Control CS 162 (Summer 2009)
Programming Abstractions Cynthia Lee CS106X. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism › Example: Expression.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Programming Abstractions Cynthia Lee CS106X. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism › Example: Expression.
CSE 143 Lecture 12 Inheritance slides created by Ethan Apter
29-July-2002cse Inheritance © 2002 University of Washington1 Inheritance CSE 142, Summer 2002 Computer Programming 1
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Copyright 2010 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading: 9.1.
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.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright 2008 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
Copyright 2009 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CSE 143 Lecture 13 Inheritance slides created by Ethan Apter
Programming Abstractions
Building Java Programs Chapter 9
Building Java Programs Chapter 9
Inheritance and Polymorphism
The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face.
Lecture 9-2: Interacting with the Superclass (super);
CS 106A, Lecture 22 More Classes
Adapted from slides by Marty Stepp and Stuart Reges
The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face.
Building Java Programs
Building Java Programs
Law firm employee analogy
Lecture 14: Inheritance Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Building Java Programs
Topic 31 - inheritance.
Building Java Programs
Inheritance Readings: 9.1.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 11 Inheritance and Encapsulation and Polymorphism
Programming Abstractions in C++, Chapter 19
Presentation transcript:

Programming Abstractions Cynthia Lee CS106B

Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism

Inheritance What? Why? How?

Inheritance: what? is-a relationship: A hierarchical connection where one category can be treated as a specialized version of another.  every rectangle is a shape  every lion is an animal type hierarchy: A set of data types connected by is-a relationships that can share common code. Re-use!

Inheritance: why?  Remember the #1 rule of computer scientists: › Computer scientists are super lazy › …in a good way!  We want to reuse code and work as much as possible  You’ve already seen this going back to the very start of your CS education: › Loops and Functions (instead of copy&paste to repeat code) › Arrays (instead of copy&paste to make 100 named variables) › Data structures (same idea as arrays but more expressive)  Inheritance is another way of organizing smart reuse of code 5

Inheritance: how? inheritance: A way to form new classes based on existing classes, taking on their attributes/behavior.  a way to group related classes  a way to share code between two or more classes One class can extend another, absorbing its data/behavior.

Inheritance vocab  superclass (base class): Parent class that is being extended.  subclass (derived class): Child class that inherits from the superclass. › Subclass gets a copy of every field and method from superclass. › Subclass can add its own behavior, and/or change inherited behavior.

Inheritance Example Stanford Library G-Object family of classes Gob-ject

Behind the scenes…  We’ve always told you not to worry about the graphics parts of your assignments. › “Just call this BoggleGUI function…”  Now you can go ahead and take a look! 9

GObject hierarchy The Stanford C++ library contains a hierarchy of graphical objects based on a common base class named GObject.  GArc  GImage  GLabel  GLine  GOval  GPolygon  GRect  G3DRect  GRoundRect hi

GObject members GObject defines the state and behavior common to all shapes:  contains(x, y)  get/setColor()  getHeight(), getWidth()  get/setLocation(), get/setX(), get/setY()  move(dx, dy)  setVisible(visible) The subclasses add state and behavior unique to them: GlabelGLineGPolygon GOval get/setFontget/setStartPointaddEdge getSize get/setLabelget/setEndPointaddVertex get/setFillColor get/setFillColor double x; double y; double lineWidth; std::string color; bool visible;

GObject members GObject defines the state and behavior common to all shapes:  contains(x, y)  get/setColor()  getHeight(), getWidth()  get/setLocation(), get/setX(), get/setY()  move(dx, dy)  setVisible(visible) The subclasses add state and behavior unique to them: GlabelGLineGPolygon GOval get/setFontget/setStartPointaddEdge getSize get/setLabelget/setEndPointaddVertex get/setFillColor get/setFillColor double x; double y; double lineWidth; std::string color; bool visible;

GObject hierarchy The Stanford C++ library contains a hierarchy of graphical objects based on a common base class named GObject.  GArc  GImage  GLabel  GLine  GOval  GPolygon  GRect  G3DRect  GRoundRect hi Q: Rectangle is-a Polygon, right? Why doesn’t it inherit from Polygon?? Although true in geometry, they don’t share many fields and methods in this case.

Inheritance Example Your turn: let’s write an Employee family of classes

Example: Employees Imagine a company with the following employee regulations:  All employees work 40 hours / week  Employees make $40,000 per year plus $500 for each year worked › Except for lawyers who get twice the usual pay, and programmers who get the same $40k base but $2000 for each year worked  Employees have 2 weeks of paid vacation days per year › Except for programmers who get an extra week Each type of employee has some unique behavior:  Lawyers know how to sue  Programmers know how to write code

16 Employee class // Employee.h class Employee { public: Employee(string name, int years); virtual int hours(); virtual string name(); virtual double salary(); virtual int vacationDays(); virtual int years(); private: string m_name; int m_years; }; // Employee.cpp Employee::Employee(string name, int years) { m_name = name; m_years = years; } int Employee::hours() { return 40; } string Employee::name() { return m_name; } double Employee::salary() { return (500 * m_years); } int Employee::vacationDays() { return 10; } int Employee::years() { return m_years; }

Exercise: Employees Exercise: Implement classes Lawyer and Programmer.  A Lawyer remembers what law school he/she went to.  Lawyers make twice as much salary as normal employees.  Lawyers know how to sue people (unique behavior).  Lawyers put “, Esq.” at the end of their name.  Programmers make the same base salary as normal employees, but they earn a bonus of $2k/year instead of $500/year.  Programmers know how to write code (unique behavior).

Inheritance syntax class Name : public SuperclassName {  Example: class Lawyer : public Employee {... }; By extending Employee, each Lawyer object now:  receives a hours, name, salary, vacationDays, and years method automatically  can be treated as an Employee by client code

Call superclass c'tor SubclassName::SubclassName(params) : SuperclassName(params) { statements; } To call a superclass constructor from subclass constructor, use an initialization list, with a colon after the constructor declaration.  Example: Lawyer::Lawyer(string name, string lawSchool, int years) : Employee(name, years) { // calls Employee constructor first m_lawSchool = lawSchool; }

Your turn: inheritance string Lawyer::name() { ??? } For adding “, Esq.” to the name, which of the following could work? A.return m_name + ", Esq."; B.return name() + ", Esq."; C.return Employee::name() + ", Esq."; D. None of the above E. More than one of the above // Employee.h class Employee { public: Employee(string name, int years); int hours(); string name(); double salary(); int vacationDays(); string vacationForm(); int years(); private: string m_name; int m_years; };

Call superclass member SuperclassName::memberName(params) To call a superclass overridden member from subclass member.  Example: double Lawyer::salary() { // paid twice as much return Employee::salary() * 2; }  Note: Subclass cannot access private members of the superclass.  Note: You only need to use this syntax when the superclass's member has been overridden. › If you just want to call one member from another, even if that member came from the superclass, you don't need to write Superclass::.

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 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