CPS 100 2.1 Anagram: Using Normalizers l How can we normalize an Anaword object differently?  Call normalize explicitly on all Anaword objects  Have.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
12/08/08MET CS Fall Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
PolymorphismCS-2303, C-Term Polymorphism Hugh C. Lauer Adjunct Professor (Slides include materials from The C Programming Language, 2 nd edition,
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
CPS What’s easy, hard, first? l Always do the hard part first. If the hard part is impossible, why waste time on the easy part? Once the hard part.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
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.
C++ Review Classes and Object Oriented Programming Parasol Lab, Texas A&M University.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
CPS Anagram: Using Normalizers l How can we normalize an Anaword object differently?  Call normalize explicitly on all Anaword objects  Have.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Programming in Java CSCI-2220 Object Oriented Programming.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
CPS What is Computer Science? What is it that distinguishes it from the separate subjects with which it is related? What is the linking thread.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object-Oriented Programming Chapter Chapter
Inheritance Revisited Other Issues. Multiple Inheritance Also called combination--not permitted in Java, but is used in C++ Also called combination--not.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
APCS Workshop 1 Why is programming fun? What delights may its practitioner expect as a reward? First is the sheer joy of making things Second is the pleasure.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Object Oriented Programming
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Overview of C++ Polymorphism
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
CompSci Reading from Files  import java.io.File;  Declare a file File fileOfCats = new File(”cats.txt”);  Use file – pass it as an argument to.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
CPS 100e 5.1 Inheritance and Interfaces l Inheritance models an "is-a" relationship  A dog is a mammal, an ArrayList is a List, a square is a shape, …
Class Relationships Lecture Oo08 Polymorphism. References n Booch, et al, The Unified Modeling Language User Guide, Chapt 10 p.125 n Fowler & Scott, UML.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Design issues for Object-Oriented Languages
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CMSC 202 Polymorphism.
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Inheritance and Polymorphism
Anagrams/Jumbles How do humans solve puzzles like that at
Polymorphism.
Review: Two Programming Paradigms
CISC/CMPE320 - Prof. McLeod
Polymorphism CMSC 202, Version 4/02.
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Overview of C++ Polymorphism
Java String Class String is a class
Lecture 6: Polymorphism
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:

CPS Anagram: Using Normalizers l How can we normalize an Anaword object differently?  Call normalize explicitly on all Anaword objects  Have Anaword objects normalize themselves  Advantages? Disadvantages? l If Anaword objects normalize themselves, how can we experiment with different normalization techniques?  Gut and paste. Problems? Versions? Saved code?  What about cp anaword.cpp oldanaword.cpp ?  What about deciding at runtime on normalization? l We need inheritance!

CPS How to normalize? Where should the code for normalizing Anaword objects live? 1. Where it’s needed. 2. In a separate function 3. In a separate funtion inside of the Anaword class 4. In its own class Why?

CPS Pointer questions In which location do dynamic variables reside? 1. The code segment. 2. The data segment. 3. The heap. 4. The run-time stack.

CPS l Consider the following statements int *p; int I; int k; I = 42; k = I; p = &i

CPS Pointer Question #2 l Consider the following code fragment int *p; int i; int k; I = 42; k = i; p = &i After these statements, which of the following statements will change the value of i to 75? 1. k = 75; 2. *k = 75; 3. p = 75; 4. *p = 75; 5. Two or more of the answers will change i to 75. Why should your code NEVER look like this?

CPS Normalizer hierarchy l Anaword objects normalize themselves  Where does the normalizer come from? Passed in at construction time Obtained from normalizer factory Other approaches?  How is Normalizer used? l Normalizer is conceptually an interface  Different implementations of the interface have different behavior (guts) but same skin (sort of)

CPS Benefits of inheritance, interfaces l Suppose you learn about a new class WebStream that conforms to the input stream interface (cin, ifstream, …)  Read words, lines, chars from a web page? void readWords(istream& input) { string s, line; char ch; getline(input,line); input >> s; input.get(ch); } l We can pass cin, ifstream, WebStream, etc. to readWords  Why is this an advantage?  Inheritance and late/dynamic binding

CPS Why inheritance? l Add new shapes easily without changing much code  Shape * s1 = new Circle();  Shape * s2 = new Square(); l abstract base class:  interface or abstraction  pure virtual function l concrete subclass  implementation  provide a version of all pure functions l “is-a” view of inheritance  Substitutable for, usable in all cases as-a shape mammal ScoreEntry FullHouse, LargeStraight User’s eye view: think and program with abstractions, realize different, but conforming implementations, don’t commit to something concrete until as late as possible

CPS Example of inheritance l What is behavior of a shape? void doShape(Shape * s) { cout area() << endl; cout perimeter() << end; s->expand(2.0); cout area() << endl; cout perimeter() << endl; } Shape * s1 = new Circle(2); Shape * s2 = new Square(4); Shape * s3 = new Rectangle(2,5);d doShape(s1); doShape(s2); doShape(s3);

CPS Inheritance (language independent) l First view: exploit common interfaces in programming  Streams in C++, iterators in Tapestry classes Iterators in STL/C++ share interface by convention/templates  Implementation varies while interface stays the same l Second view: share code, factor code into parent class  Code in parent class shared by subclasses  Subclasses can override inherited method Can subclasses override and call? l Polymorphism/late(runtime) binding (compare: static)  Actual function called determined when program runs, not when program is compiled

CPS Inheritance Heuristics l A base/parent class is an interface  Subclasses implement the interface Behavior changes in subclasses, but there’s commonality  The base/parent class can supply some default behavior Derived classes can use, override, both l Push common behavior as high up as possible in an inheritance hierarchy l If the subclasses aren’t used polymorphically (e.g., through a pointer to the base class) then the inheritance hierarchy is probably flawed

CPS Normalizer details (see Anaword) l What’s static? Why private? Static initialization? class Anaword { public: // not shown private: void normalize(); static Normalizer * ourNormalizer; }; void Anaword::normalize() // postcondition: mySortedWord is sorted version of myWord { if (ourNormalizer == 0) { ourNormalizer = NormFactory::getNormalizer(); } myNormalizedWord = ourNormalizer->normalize(myWord); }

CPS Guidelines for using inheritance l Create a base/super/parent class that specifies the behavior that will be implemented in subclasses  Most/All functions in base class may be virtual Often pure virtual (= 0 syntax), subclasses must implement  Subclasses do not need to specify virtual, but good idea May subclass further, show programmer what’s going on  Subclasses specify inheritance using : public Base C++ has other kinds of inheritance, stay away from these  Must have virtual destructor in base class l Inheritance models “is-a” relationship, a subclass is-a parent-class, can be used-as-a, is substitutable-for  Standard examples include animals and shapes

CPS Inheritance guidelines/examples l Virtual function binding is determined at run-time  Non-virtual function binding (which one is called) determined at compile time  Need compile-time, or late, or polymorphic binding  Small overhead for using virtual functions in terms of speed, design flexibility replaces need for speed Contrast Java, all functions “virtual” by default l In a base class, make all functions virtual  Allow design flexibility, if you need speed you’re wrong, or do it later l In C++, inheritance works only through pointer or reference  If a copy is made, all bets are off, need the “real” object

CPS Student behavior/interface?.h file class Student { public: Student(const string & name); virtual ~Student(); virtual void eat(); virtual void work(); virtual void sleep(); virtual void live(); bool isAlive() const; // more here

CPS Implementation of behavior,.cpp file void Student::sleep() { myEnergy += 10; cout << "Zzzzzzzzzzzzz, resting sleep" << endl; } void Student::live() { eat(); work(); sleep(); }

CPS See students.cpp, school.cpp l Base class student doesn’t have all functions virtual  What if subclass has different name() function? name() bound at compile time, no change observed How do subclass objects call parent class code, see DukeStudent class in school.cpp  class::function syntax, must know name of parent class l Why is base class data protected rather than private?  Must be accessed directly in subclasses, why?  Not ideal, try to avoid state in base/parent class: trouble What if derived class doesn’t need data?

CPS Inheritance Heuristics in C++ l Pure virtual (aka abstract) function makes a class abstract  Cannot be instantiated, but can be constructed (why?) What do subclasses do?  Default in C++ is non-virtual or monomorphic Unreasonable emphasis on efficiency, sacrifices generality If you think subclassing will occur, all methods are virtual  Must have virtual destructor, the base class destructor (and constructor) will be called l We use public inheritance, models is-a relationship  Private inheritance means is-implemented-in-terms-of Implementation technique, not design technique Not ubiquitous in other languages

CPS Difference in behavior? l What’s a field and what’s a method?  # tires on car?  # doors on car?  How student lives? l Where does name of school belong? What about energy increment? l What’s problem with hierarchy here?  NCState student? Student DukeStudent UNCStudent CosmicDukeStudent CosmicUNCStudent

CPS Problems with inheritance l Consider the student example and burrito eating  CosmicStudent is a subclass of DukeStudent What behavior changes in the new subclass?  What about a UNCStudent eating cosmic cantina food? Can we have CosmicDukeStudent and CosmicUNCStudent? Problems with this approach? l Alternative to inheritance: use delegation (aka layering, composition)  Just like myEnergy is a state variable with different values, make myEater a state variable with different values  Delegate behavior to another object rather than implementing it directly

CPS Delegation with school/student l If there's a class Eater, then what instance variable/field will a Student store to which eating behavior delegated? void Student::eat() { myEater->doEat(); }  How is the eater instance variable initialized?  Could we adopt this approach for studying too?  When is this approach better/worse?

CPS Problem Solving l Some believe that being a good programmer will be a prerequisite for being a good mathematician  Computer-aided proofs are big (four color theorem, Kepler’s conjecture)  Computer programs are very formally complete and precise l Teachers often speak of a magical “problem solving intuition” l Does such a thing exist? l Is it really just experience and pattern recognition? l What are some tools to help learning programmers to solve problems?

CPS Dropping Glass Balls l Tower with N Floors l Given 2 glass balls l Want to determine the lowest floor from which a ball can be dropped and will break l How? l What is the most efficient algorithm? l How many drops will it take for such an algorithm (as a function of N)?

CPS Pairing-up students l Assume you have n students (n is even) l You would like to have lab sections in which every student has a partner to work with for that particular lab section l As there are n students, this can be done in n -1 days optimally l How? l Dead-end solution with 6 people  Day 1: [1 pairs with 2] [3 pairs with 4] [5 pairs with 6]  Day 2: [1 pairs with 3] [2 pairs with 4] … uh oh