Class Inheritance Victor Norman CS104. The Problem What is the basic problem that inheritance tries to solve? Answer: Two types (classes) may have lots.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Chapter 14 Graph class design John Keyser’s Modifications of Slides by Bjarne Stroustrup
Class Inheritance Victor Norman CS104. Reading Quiz, Q1 In the first reading, the author uses the following classes to illustrate Subclassing: A.Shape,
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.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
More about classes and objects Classes in Visual Basic.NET.
CSE341: Programming Languages Lecture 22 Multiple Inheritance, Interfaces, Mixins Dan Grossman Fall 2011.
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 Chapter 8.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
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.
CPSC150 Interfaces Chapter CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class.
Object-oriented Programming Concepts
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 1 Introduction to Object-Oriented Programming and Software Development.
Computer Science I Inheritance Professor Evan Korth New York University.
Lilian Blot INHERITANCE Object Oriented Programming Spring 2014 TPOP 1.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Abstract classes and Interfaces. Abstract classes.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Inheritance: Section 9.1, 9.2 Victor Norman CS106.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
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.
Data Structures for Scenes, The Basics of Scene Graphs Glenn G. Chappell U. of Alaska Fairbanks CS 481/681 Lecture Notes Friday,
CSC 211 Introduction to Design Patterns. Intro to the course Syllabus About the textbook – Read the introduction and Chapter 1 Good attendance is the.
Python Programming in Context Chapter 12. Objectives To introduce the concept of inheritance To create a working object-oriented graphics package To provide.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Copyright (c) 1998, 1999 D.L. Bailey * Winter 1999 Part 6 Reusing Classes: Inheritance and Composition.
Object Oriented Software Development
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
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)
CS 350 – Software Design Expanding Our Horizons – Chapter 8 The traditional view of objects is that they are data with methods. Sometimes objects could.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Coming up: Inheritance
29-July-2002cse Inheritance © 2002 University of Washington1 Inheritance CSE 142, Summer 2002 Computer Programming 1
Composite A robot made of smaller robots.. * * Line with open diamond at the end means “aggregates”. Basically, it’s saying that the Component objects.
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,
Student Q and As from 5.1 – 5.7, 5.11 Students of CS104, Fall 2013 (and me)
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.
7-2 Similar Polygons Objectives Students will be able to:
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com.
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.
SUBCLASSES - JAVA. The Purpose of Subclasses Class Farm String getOwner() void setOwner(String s) int getSize() void setSize(int s) Class DairyFarm String.
CPS120: Introduction to Computer Science Lecture 16A Object-Oriented Concepts.
 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
CS 5010 Program Design Paradigms "Bootcamp" Lesson 9.3
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Week 6 Object-Oriented Programming (2): Polymorphism
Object-Oriented PHP (1)
Terry Scott University of Northern Colorado 2007 Prentice Hall
Presentation transcript:

Class Inheritance Victor Norman CS104

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.

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): # code for drawArms # code for drawBody 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): # code for drawArms # code for drawBody 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, gen): self._x = x self._y = y self._gender = gen def draw(self): self.drawHead() self.drawBody() self.drawArms() self.drawLegs() # drawHead, Body, Arms code… 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() # drawHead, Body, Arms code… def drawLegs(self):

Evaluate this solution + Much less code in Person than in Man + Woman. + Only 1 class. (Less is almost always better.) − Does not scale 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() If we decide to drawHeads differently we need a big if-elif-elif again… and same for drawBody()…

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/code “pushed” up the hierarchy. – e.g., Man, Woman, Alien all have x, y location: should be stored in Person superclass.

Person Class 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, drawBody, drawArms, etc. # 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 barack = Man(10, 20) beyonce = Woman(30, 40) e_t = Alien(50, 60) beings = [ barack, beyonce, 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?

myro.py details myro library provides move(), motors(), turnLeft(), turnRight(), setLEDs(), beep(), etc. – When you call move(), you are actually calling robot.move(): robot is a pre-defined global object. Also, provides a class definition: class Scribbler: def __init__(self): … def init(self, comport=None): … def turnLeft(self, time): … def beep(self, time, freq1, freq2=None): …

What we did last week We defined ScribPoint – attributes: _x, _y – getX(), getY(), setX(), setY() – Just held the coordinates. Not much fcnality. We defined goToPoint(from, to): – from and to were ScribPoint objects. – used our turnDegrees(), which called turnLeftDegrees() or turnRightDegrees(), which used globally pre-defined robot object.

Analysis of this solution ScribPoint has very little functionality. We had to make the robot turn east after moving to a new point. – More turns  more inconsistent results. Had to pass in to goToPoint() where the robot was.

Better way Wouldn’t it be loverly if – the robot could “remember” where it is and what angle it is pointing at. But, how to do this? Two options: – Have a class that “has-a” a reference to a Scribbler object and keeps track of this stuff, or, – Have a class that “is-a” Scribbler object, adding the functionality and attributes. Latter is Class Inheritance.

CS104Scribbler A CS104Scribbler “is-a” Scribbler. – inherits from it. from myro import * # imports Scribbler defn. class CS104Scribbler(Scribbler): def __init__(self, comport=“COM40”, x=0, y=0, angle=0): Scribbler.__init__(self, comport) # code to store x, y, angle.

Result We can move goToPoint(), turnDegrees(), etc., into CS104Scribbler class.  Can write this nice code: scrib = CS104Scribbler() # uses COM40 scrib.goToPoint(16, 12) scrib.goToPoint(0, 0) Nice and compact and readable. goToPoint() does not have to “turn east” after each move, because object can remember what angle it is pointing.

Additional Benefits We could write code to control 2 robots: scrib1 = CS104Scribbler(“COM40”) scrib2 = CS104Scribbler(“COM41”) # send different messages to robots scrib1.beep(3, 660, 770) scrib2.beep(3, 440, 487)

Extra Slides…

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.

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.