Inheritance: Section 9.1, 9.2 Victor Norman CS106.

Slides:



Advertisements
Similar presentations
Class Inheritance Victor Norman CS104. Reading Quiz, Q1 In the first reading, the author uses the following classes to illustrate Subclassing: A.Shape,
Advertisements

Clean code. Motivation Total cost = the cost of developing + maintenance cost Maintenance cost = cost of understanding + cost of changes + cost of testing.
CS 2430 Day 28. Announcements Program 5 was posted (on Tuesday, 4/2/2013) Can work with a partner (sign up by today at 3:52pm) Exam 2 handed back on Monday.
Classes and Inheritance. 2 As the building blocks of more complex systems, objects can be designed to interact with each other in one of three ways: Association:
CS 211 Inheritance AAA.
Inheritance & Classification Hierarchies Lecture-8.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
1 Inheritance and Polymorphism. 2 This section is not required material!!!!  A note about inheritance… It’s not normally covered in 101 It will be gone.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
More about classes and objects Classes in Visual Basic.NET.
1 Software Testing and Quality Assurance Lecture 12 - The Testing Perspective (Chapter 2, A Practical Guide to Testing Object-Oriented Software)
Object-Oriented PHP (1)
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,
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
Inheritance Chapter 8.
16/22/2015 2:54 PM6/22/2015 2:54 PM6/22/2015 2:54 PMObject-Oriented Development Concept originated with simulating objects and their interactions. Adapted.
OOP! POO! Spelled backwards. Intro to OOP What is OOP?  Stands for Object Oriented Programming  Create different types of objects which can do multiple.
Computer Science I Inheritance Professor Evan Korth New York University.
Lilian Blot INHERITANCE Object Oriented Programming Spring 2014 TPOP 1.
PRJ566: PROJECT PLANNING AND MANAGEMENT Class Diagrams.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Classes and Objects, Part 1 Victor Norman CS104. Reading Quiz, Q1 A class definition define these two elements. A. attributes and functions B. attributes.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
CS 350 – Software Design The Object Paradigm – Chapter 1 If you were tasked to write code to access a description of shapes that were stored in a database.
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
CS305j Introduction to Computing Inheritance and Polymorphism 1 Topic 26 Introduction to Inheritance and Polymorphism "One purpose of CRC cards [a design.
Data Structures for Scenes, The Basics of Scene Graphs Glenn G. Chappell U. of Alaska Fairbanks CS 481/681 Lecture Notes Friday,
Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design Guidelines.
Python Programming in Context Chapter 12. Objectives To introduce the concept of inheritance To create a working object-oriented graphics package To provide.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Object Oriented Software Development
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Classes & Inheritance Review
Inheritance Notes Chapter 6 1. Inheritance  you know a lot about an object by knowing its class  for example what is a Komondor? 2
CSCI-383 Object-Oriented Programming & Design Lecture 10.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Coming up: Inheritance
29-July-2002cse Inheritance © 2002 University of Washington1 Inheritance CSE 142, Summer 2002 Computer Programming 1
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Chapter 17 Q and A Victor Norman, et al. CS104. What is Object-oriented Programming? Q: What is object-oriented programming? A: It means defining classes/objects,
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.
1 Inheritance Inheritance is a natural way to model the world in object-oriented programming. It is used when you have two types of objects where one is.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
1 Inheritance and Polymorphism Chapter 11 Spring 2007 CS 101 Aaron Bloomfield.
Georgia Institute of Technology Comic Strip Analysis and Design Inheritance, Abstract Classes, and Polymorphism part1 Barb Ericson Georgia Institute of.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Class Inheritance Victor Norman CS104. The Problem What is the basic problem that inheritance tries to solve? Answer: Two types (classes) may have lots.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
The Object-Oriented Thought Process Chapter 1
CS-104 Final Exam Review Victor Norman.
Road Map Inheritance Class hierarchy Overriding methods Constructors
To Get Started Paper sheet
Domain Class Diagram Chapter 4 Part 2 pp
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Object-Oriented PHP (1)
Terry Scott University of Northern Colorado 2007 Prentice Hall
Presentation transcript:

Inheritance: Section 9.1, 9.2 Victor Norman CS106

The Problem What is the basic problem that inheritance tries to solve? Answer: Two types (classes) may have lots of similar code. Inheritance is a way to reuse code, thus removing duplicate code.

Deck and Hand Consider: Deck and Hand. Deck:Hand: – _cards list-- _cards list – addCard()-- addCard() – sort()-- sort() – shuffle()-- shuffle() – getNumCards()-- getNumCards() – removeCard()-- removeCard() Lots of similar functionality.

Drawing Man and Woman class Man: def __init__(self, x, y): self._x = x self._y = y def draw(self): self.drawHead() self.drawBody() self.drawArms() self.drawLegs() def drawHead(self): def drawLegs(self): class Woman: def __init__(self, x, y): self._x = x self._y = y def draw(self): self.drawHead() self.drawBody() self.drawArms() self.drawLegs() def drawHead(self): def drawLegs(self):

Lots of duplicate code So what? Who cares? Duplicate code  – more places to make errors – more places to fix errors – inconsistent fixes – more typing – more places to add new code

Solution: a Person class instead of Man/Woman class Person: def __init__(self, x, y, sex): self._x = x self._y = y self._gender = sex def draw(self): self.drawHead() self.drawBody() self.drawArms() self.drawLegs() def drawHead(self): def drawLegs(self): if self._gender == "F": self.drawSkirtAndLegs() else: self.drawHairyLegs() def drawHairyLegs(self): def drawSkirtAndLegs(self): class Man: def __init__(self, x, y): self._x = x self._y = y def draw(self): self.drawHead() self.drawBody() self.drawArms() self.drawLegs() def drawHead(self): def drawLegs(self):

Evaluate this solution + Much less code! + Only 1 class. (Less is almost always better.) − Does not scale as well: Consider: adding Alien now: 3 legs, that bend backwards. def drawLegs(self): if self._gender == “F”: self.drawSkirtAndLegs() elif self._gender == “M”: self.drawHairyLegs() elif self._gender == “A”: self.drawAlienLegs()

Solution: class inheritance Keep Person, and make Man, Woman, and Alien be subclasses Person Man Woman Alien

Terminology Person is the superclass, or base class, or parent class. Man, Woman, Alien are subclasses, derived classes, or child classes. Subclasses inherit from or are derived from superclasses. Want all common attributes and methods “pushed” up the hierarchy. – e.g., Man, Woman, Alien all have x, y location: should be stored in Person superclass.

Code class Person: # an abstract base class. def __init__(self, x_loc, y_loc, gender): self._x = x_loc self._y = y_loc self._gender = gender def draw(self): self.drawHead() self.drawBody() self.drawArms() self.drawLegs() def drawHead(self): # NOTE: No drawLegs() code here. Only in # derived classes. Also, don’t really need # to store gender anymore.

Man class Man(Person): def __init__(self, x_loc, y_loc): Person.__init__(self, x_loc, y_loc, "M") def drawLegs(self): # code to draw hairy bowlegged legs wearing jeans. “A Man is-a Person” Call superclass constructor, passing in reference to self, location and gender drawLegs() implemented here – not in superclass

Woman, Alien from person import * # assuming Person is in person.py class Woman(Person): def __init__(self, x_loc, y_loc): Person.__init__(self, x_loc, y_loc, “F”) def drawLegs(self): # code to draw legs under a nice modest skirt. class Alien(Person): def __init__(self, x_loc, y_loc): Person.__init__(self, x_loc, y_loc, "A") def drawLegs(self): # code to draw 3 legs.

Using this code (PythonTutor visualization)visualization aaron = Man(10, 20) chris = Woman(30, 40) e_t = Alien(50, 60) beings = [ aaron, chris, e_t ] for be in beings: be.draw()

Now, you try it! We want to create a program that the user can use to draw shapes, etc. We need to model these shapes: – Circle – Square – Rectangle – Line – Triangle What is the relationship between classes? (the class hierarchy) What attributes will each class have? What methods will each class have?

New class or child class? Q: If a class needs a couple attributes belonging to another class, is it better to make a child class or a completely new class? A: If it is just attributes, just make a new class. If it is attributes and a bunch of functionality, make a subclass.

When to subclass? Q: When would it be better to use the Parent and Child class rather than defining methods in one class? A: 1) You might need to be able to make objects of both kinds of classes. 2) You might have the Parent class well tested – so you don’t want to alter it. 3) You anticipate that you might need another child class of the parent.

SortedSet Q: I am wondering why a whole separate class is created for some of these functions. For stuff like SortedSet, the case can be made, but I feel like we can accomplish the same thing with a “plain old list” and functions contained in that class. A: I agree. The example is a bit contrived. I would have started from scratch with a class containing a list.

SortedSet (2) Q: So the "sort" method is created just to prevent people from sorting the already sorted set? And why wouldn't we want to reverse it? A: Right. sort’s code consists of pass. This is done so that it is efficient, instead of trying to sort an already sorted list. You don’t want to reverse it because then it is not sorted anymore. NOTE: when you find you are “undefining” methods provided by the superclass, this should be an indication that you’ve made a poor inheritance decision.

How to see defined methods? Q: Is there a way to see all the preexisting methods for a parent class? A: Best way is to do >>> help(class) in interactive mode.

What does this do? Q: Are we modifying the class Television or the class DeluxeTV with this def? class DeluxeTV(Television): def __init__(self): Television.__init__(self) self._favorites = [ ] A: You are modifying the DeluxeTV class – adding _favorites to it.

__setitem__ Q: What is going on with the __setitem__ method? A: __setitem__ is called when you do indexing: __setitem__(...) x.__setitem__(i, y) x[i]=y

Example class Vic: def __init__(self): self._l = [] def __setitem__(self, loc, item): if len(self._l) > loc: self._l[loc] = item else: numItemsToAdd = loc - len(self._l) for i in range( numItemsToAdd): self._l.append(0) self._l.append(item) v = Vic() v[0] = "hi" v[3] = "hello" print v._l OUTPUT: ['hi', 0, 0, 'hello']

“Inner” classes Q: Is it possible to have a class in a class? A: It is possible, but I’ve never had to do it.