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:

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
OBJECT-ORIENTED PROGRAMMING. What is an “object”? Abstract entity that contains data and actions Attributes (characteristics) and methods (functions)
Inheritance (notes for 10/26 lecture). Inheritance Inheritance is the last of the relationships we will study this semester. Inheritance is (syntactically)
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
CS 106 Introduction to Computer Science I 11 / 19 / 2007 Instructor: Michael Eckmann.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Guide to Programming with Python
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
CIT 590 Intro to Programming Style Classes. Remember to finish up findAllCISCourses.py.
Inheritance: Section 9.1, 9.2 Victor Norman CS106.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
CPSC1301 Computer Science 1 Chapter 11 Creating Classes part 1.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
Practical Object-Oriented Design with UML 2e Slide 1/1 ©The McGraw-Hill Companies, 2004 PRACTICAL OBJECT-ORIENTED DESIGN WITH UML 2e Chapter 9: Interaction.
Georgia Institute of Technology Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
CSC 142 Computer Science II Zhen Jiang West Chester University
Inheritance Building one object from another. Background Object-oriented programming is normally described has offering three capabilities Encapsulation:
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
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.
Design.ppt1 Top-down designs: 1. Define the Problem IPO 2. Identify tasks, Modularize 3. Use structure chart 4. Pseudocode for Mainline 5. Construct pseudocode.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
Object Oriented Software Development
CSC 205 Java Programming II Inheritance Inheritance In the real world, objects aren’t usually one-of-a-kind. Both cars and trucks are examples of.
Classes & Inheritance Review
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Inheritance and Access Control CS 162 (Summer 2009)
Mechanisms for Reuse CMPS OOP billed as technology that permits software to be constructed from general-purpose reusable components Two main mechanisms.
Object-Oriented Programming Chapter Chapter
C++ Inheritance Data Structures & OO Development I 1 Computer Science Dept Va Tech June 2007 © McQuain Generalization versus Abstraction Abstraction:simplify.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 12 Inheritance and Class Design 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 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 5JA Introduction to Java Pop Quiz Define/Explain encapsulation. In object-oriented programming, encapsulation refers to the grouping of data and the.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
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.
SUBCLASSES - JAVA. The Purpose of Subclasses Class Farm String getOwner() void setOwner(String s) int getSize() void setSize(int s) Class DairyFarm String.
Class Inheritance Victor Norman CS104. The Problem What is the basic problem that inheritance tries to solve? Answer: Two types (classes) may have lots.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CMSC201 Computer Science I for Majors Lecture 18 – Classes and Modules (Continued, Part 3) Prof. Katherine Gibson Based on slides from the.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Guide to Programming with Python
Lecture 12 Inheritance.
Adapted from slides by Marty Stepp and Stuart Reges
Adapted from slides by Marty Stepp and Stuart Reges
Adapted from slides by Marty Stepp and Stuart Reges
Lecture VI Objects The OOP Concept Defining Classes Methods
Object-oriented programming
Understanding Inheritance
Adapted from slides by Marty Stepp and Stuart Reges
Two big words Inheritance Polymorphism
Object-Oriented Programming
Prof. Katherine Gibson Prof. Jeremy Dixon
Inheritance Lakshmish Ramaswamy.
Presentation transcript:

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: an object is aware of another object and holds a reference to it Composition: objects combining to create more complex ones Inheritance: classes (types) are defined as extensions of other classes Relationships Between Classes

3 In an associative has-a relationship, an object is aware of another complex object and can communicate with it. Example: a Car has an owner attribute which is a Person. Association CarownerPersonnameagegender

4 In a compositional has-a relationship, an object is made up of other objects. Example: a Movie object might be composed of str objects title and genre and int object year. Composition Movietitlegenreyear

5 Inheritance Inheritance, as opposed to the previous two examples, is not a has- a relationship. It's an is-a relationship. It means that objects of a particular class are members of a subset of the objects of another class. The subclass inherits all the properties of the superclass, and adds some of its own. Inheritance is a largely misunderstood idea, so we will spend a bit of time clarifying when it is useful and when it is not.

6 Inheritance example Consider the class Person: class Person(): def __init__(self, n, y, g): self.name = n self.year = y self.gender = g Several modules may use this class to keep track of Person objects. Now, imagine that the university would like to use the Person class to store information about its students.

7 Inheritance example The Person class does not have all the attributes necessary to keep track of a student's personal information. What can we do? We could add what we need to Person, which, if done by all other methods that may be using Person, would make Person a very long, unwieldy class. Alternatively, we can create the parts that we're missing (student number, GPA, etc.) in another class and connect it to the Person class somehow.

8 The Student Class We create the class Student: class Student(???): def __init__(self, stn, avg): self.student_number = stn self.gpa = avg Now, this Student class also needs a name, a gender and a year of birth. We have three options.

9 The Student Class - Option A Copy and paste the code: class Student(object): def __init__(self, n, y, g, s, a): self.name = n self.year = y self.gender = g self.student_number = s self.gpa = a This option makes all the Person functionality available in the Student class, but it has a drawback: if a new attribute needed to be added for all people, it would have to be added in two places. Also, if improvements are made to Person, they are not automatically done in Student.

10 The Student Class - Option B Here, we use composition. class Student(object): def __init__(self, n, a, p): self.student_number = n self.gpa = a self.person = p This option makes the Student class store a Person object. This way, looking for the Student's name would involve checking its person attribute's name. However, this is counter-intuitive as a metaphor since the student is not a separate entity from the person. It's not that students HAVE people, students ARE people.

11 The Student Class - Option C There was a way to express that every Student is a Person with extra information: students are a subset of people. We specify that Student inherits from Person by giving Person as a parameter to the class definition: class Student(Person): This means that the Student class automatically takes on all the properties of the Person class before any of its own are even defined.

12 The Student Class Then, we add what we're missing and pass on pertinent information to our parent/ancestor/superclass: class Student(Person): def __init__(self, n, y, g, sn, a): Person.__init__(self, n, y, g) self.student_number = sn self.gpa = a The highlighted line calls the Person constructor, initializing the Person-specific parts of our Student.

13 Inheriting Attributes Let's make a new Student: >>> ramona = Student("Ramona", 1987, 'F', , 3.0) Our student has student-specific attributes: >>> ramona.gpa 4.0 She also has all the attributes a person may have: >>> ramona.name Ramona

14 Inheriting Methods All the Person's methods are now Student methods as well, so if Person had a __str__: def __str__(self): return "%s (%s) b. %s" % \ (self.name, self.gender, self.year) Even though we haven't specifically defined a __str__ method in Student, we have one: >>> print ramona Ramona (F) b. 1987

15 Overriding Methods It's natural that a Student's string representation would be different from a Person's. So, if we wrote a __str__ method for Student: def __str__(self): return "Student %s (%s)" % \ (self.name, self.student_number) This method would override (be called instead of) any method of the same name from its ancestor: >>> print ramona Student Ramona ( )

16 Overriding Methods When overriding, we can still rely on the parent's method to do part of the work: def __str__(self): return "Student %s (%s)" % \ (Person.__str__(self), self.student_number) Then, Person’s __str__ method would help build the result of Student’s __str__ method. >>> print ramona Student Ramona (F) b ( )

17 Extending Functionality We will want to do things with Students that don't apply to all Persons. So, by writing methods in the Student class itself, we can extend functionality without affecting Person: # Inside class Student: def raise_gpa(self, bonus): self.gpa += bonus >>> ramona.raise_gpa(0.5) >>> ramona.gpa 3.5 >>> velian = Person("Velian", 1986,'M') >>> velian.raise_gpa(0.5) <-- ERROR

18 Inheritance: Conclusion Inheritance is one of the most powerful concepts in object-oriented programming, but it's also one of the most abused. When we say that class B inherits from class A, we are making a very specific claim about the relationships between these two objects: We are claiming that the objects in class B are a subset of the objects of class A, and have all their properties and more. Cars are objects. People own cars. Why don't we let Person inherit from Car to represent people who own cars? A person is not a type of car!