CSC 143N 1 CSC 143 Object-Oriented Programming [Chapter 8]

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Advertisements

Session 07: C# OOP 4 Review of: Inheritance and Polymorphism. Static and dynamic type of an object. Abstract Classes. Interfaces. FEN AK - IT:
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.
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Abstract Classes and Interfaces
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
LECTURE 07 Programming using C# Inheritance
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
What is inheritance? It is the ability to create a new class from an existing class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 10 Inheritance and Polymorphism
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Overview of C++ Polymorphism
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Inheritance and Polymorphism
Object-Oriented Programming: Inheritance and Polymorphism.
Inheritance in C++ Bryce Boe 2012/08/28 CS32, Summer 2012 B.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
258 3/30/98 CSE 143 Object-Oriented Programming [Chapter 11]
ISBN Chapter 12 Support for Object-Oriented Programming.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
 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.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Polymorphism.
CSC 143 Inheritance.
Week 6 Object-Oriented Programming (2): Polymorphism
Java Programming, Second Edition
Fundaments of Game Design
Chapter 9 Carrano Chapter 10 Small Java
Overview of C++ Polymorphism
Lecture 10 Concepts of Programming Languages
Chapter 11 Inheritance and Encapsulation and Polymorphism
C++ Object Oriented 1.
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:

CSC 143N 1 CSC 143 Object-Oriented Programming [Chapter 8]

CSC 143N 2 Introduction  Classes have given us tremendous benefit  Encapsulation: make details of implementation and representation private  Classes help break down and organize the task of writing a program  Classes are designed to enable other benefits  Inheritance (subclassing)  Dynamic dispatch (polymorphism)  Two very powerful programming tools!  They help us write less code

CSC 143N 3 Classes Using Other Classes  We've seen one way that a class can make use of another class  Use an instance of that class as a member variable class PolyLine { private: PointArray pa; };  We might call this a "has-a" relationship  A PolyLine "has-a" PointArray

CSC 143N 4 Hierarchies of Organization (1)  Often, we classify things in a hierarchy from general to specific Animal MammalFishReptile Canine Feline Dog Tuna Wolf Cat Shark Croc Iguana

CSC 143N 5 Hierarchies of Organization (2)  Objects have more of a "is-a-kind-of" relationship  A Dog "is-a-kind-of" Canine, a Shark "is-a-kind- of" Animal  This is often just called a “is-a” relation

CSC 143N 6 Inheritance  Inheritance is a way to encode the "is-a-kind-of" relation in OO languages  Shark declares that it "is-a-kind-of" Fish by inheriting from it  A derived class inherits from a base class by putting " : public BaseClassName " in the class declaration class Shark : public Fish { // Shark-specific stuff here }; derived class (or subclass) base class (or superclass)

CSC 143N 7 Example: A Point Class  Let's say we had the following class class Point { public: Point( double x, double y ); double getX(); double getY(); void print( ostream& os ); private: double xpos; double ypos; };  We can use inheritance to create a class of colored points based on this class

CSC 143N 8 ColorPoint with inheritance (1)  ColorPoint "is-a" Point  Therefore ColorPoint has to be able to do anything Point can:  use class ColorPoint : public Point  All fields and methods of Point are "inherited" by ColorPoint - they are transparently included!  Derived class can add new methods, fields  Derived class can override base class behavior

CSC 143N 9 ColorPoint with inheritance (2) class ColorPoint : public Point { public: ColorPoint( double x, double y, Color c); //getX() is inherited from Point //getY() is inherited from Point //New accessor method for the Color field Color getColor(); //We still need to redefine //the print method! void print( ostream& os ); private: // xpos is inherited from Point // ypos is inherited from Point Color color;};

CSC 143N 10 Rules of Inheritance  All data and methods in base class (superclass) are automatically inherited by derived (sub) class  Changes in base class are automatically propagated into derived classes  Public members of base class visible to derived class and clients that use it  Private members of base class still not visible to derived class or clients  Can also declare “protected” members in base class which are visible in derived class, but not visible to clients.

CSC 143N 11 ColorPoint::ColorPoint( double x, double y, Color c ) : Point( x, y ) { color = c; } Color ColorPoint::getColor() { return color; } void ColorPoint::print( ostream& os ) { os << "(" << getX() << ", " << getY() << "), " << color; } ColorPoint Implementation  New notation: “: member(values, …)” specifies base class constructor to initialize base class fields in derived class object

CSC 143N 12 ColorPoint Client Point p( 1.0, 0.0 ); ColorPoint cp1( 3.14, -45.5, RED ); // No problem: ColorPoint::print is defined cp1.print( cout ); // No problem: calls Point::getX() and Point::getY() // on Point subset of ColorPoint to access private // xpos and ypos fields cout << cp1.getX() << " " << cp1.getY() << endl; // p can refer to any Point, including one that is // actually a ColorPoint. But p can only be used to // access fields that belong to all Points (i.e., // can’t be used to access getColor) p = cp1;

CSC 143N 13 Invoking Overriden Methods  Observation: ColorPoint::print does the same thing as Point::print, and then prints out a Color  So perhaps we can call Point::print from within ColorPoint::print  What happens if we try it this way? void ColorPoint::print( ostream& os ) { // trying to call print method in superclass print( os ); os << ", " << Color; }

CSC 143N 14 Scope Resolution  It turns out that the :: operator allows us to explicitly call an overriden method from the derived class void ColorPoint::print( ostream& os ){ Point::print( os ); os << ", " << Color; }  BaseClass::method(arguments) can be used as long as BaseClass really is a parent class (either direct base class or more distant ancestor)

CSC 143N 15 Inheritance and Constructors  Constructors are not inherited!  Can’t be, because their name specifies which class they’re part of!  Instead, constructor of base class is called automatically before constructor of derived class  Can indicate base class constructor explicitly using the “:class(arguments)” notation to pass parameters (like in ColoredPoint example)  If omitted, default constructor of base class is called  Constructors are called in "inside-out" order

CSC 143N 16 Substituting Derived Classes  Recall that an instance of a derived class can always be substituted for an instance of a base class  Derived class guaranteed to have (at least) the same data and interface as base class  But you may not get the behavior you want! Point p( 1.0, 9.0 ); ColorPoint cp( 6.0, 7.0, red ); p = cp; void printPoint( Point pt ) { pt.print( cout ); } printPoint( p ); printPoint( cp );

CSC 143N 17 Pointers And Inheritance  You can also substitute a pointer to a derived class for a pointer to a base class  There's still that guarantee about data and interface  Also holds for reference types  No information disappears!!  Unfortunately, we still have the same problems… Point *pptr = new Point( 1.0, 9.0 ); ColorPoint *cpptr = new ColorPoint( 6.0, 7.0, red ); Point *fooptr = cpptr; void printPoint( Point *ptr ) { ofstream ofs( "point.out" ); ptr->print( ofs ); ofs.close(); } printPoint( pptr ); printPoint( cpptr );

CSC 143N 18 Static And Dynamic Types  In C++, every variable has a static and a dynamic type  Static type is declared type of variable Every variable has a single static type that never changes  Dynamic type is type of object the variable actually contains or refers to Dynamic type can change during the program!  Up to now, these have always been identical  But not any more! Point *myPointPointer = new ColorPoint( 3.14, 2.78, green );

CSC 143N 19 Static Dispatch  "Dispatching" is the act of deciding which piece of code to execute when a method is called  Static dispatch means that the decision is made statically, i.e. at compile time  Decision made based on static type of receiver Point *myPointPointer = new ColorPoint( 3.14, 2.78, green ); // myPointPointer is a Point*, so call Point::print myPointPointer->print( cout );  Idea: make the decision at runtime, based on the dynamic type of the object

CSC 143N 20 Dynamic Dispatch  C++ has a mechanism for declaring individual methods as dynamically dispatched  If an overriding function exists, call it  In base class, label the function with virtual keyword  Overriding versions in subclasses may or may not have the virtual keyword; but use consistently for better style  Rule of thumb: If you may ever need to override a method, make it virtual!  Even safer rule: Unless you have a good reason not to, member functions in a class hierarchy should be virtual.

CSC 143N 21 Example Of Dynamic Dispatch class Point { public: virtual void print( ostream& os ); … }; class ColorPoint : public Point { public: virtual void print( ostream& os ); … }; Point *p = new ColorPoint( 3.13, 5.66, ORANGE); p->print( cout ); // calls ColorPoint::print( )

CSC 143N 22 Dynamically-Dispatched Calls  The compiler notices that Point::print is defined as virtual  Instead of just calling Point::print, it inserts extra code to look at information attached to the object by new to decide what function to call  This is slightly slower than static dispatch  Almost always too minor a speed penalty to worry about Point *p = new ColorPoint( 3.13, 5.66, ORANGE); p->print( cout );

CSC 143N 23 A User-Interface Example class Widget { public: void getPosition( int& x, int& y ); virtual void draw( Screen& theScreen ); … private: int xpos, ypos; }; class Button : public Widget { public: virtual void draw( Screen& theScreen ); … }; class Toolbar : public Widget { public: virtual void draw( Screen& theScreen ); };  Many user interface toolkits are implemented as class hierarchies  Helps manage complexity  Question: how should we implement Widget::draw ?

CSC 143N 24 Abstract Classes  Some classes are so abstract that instances of them shouldn't even exist  What does it mean to have an instance of Widget ? of Animal ?  An abstract class is one that should not or can not be instantiated - it only defines an interface  A concrete class can have instances  It may not make sense to attempt to fully implement all functions in an abstract class  What should Widget::draw do?

CSC 143N 25 Pure Virtual Functions (1)  A “pure virtual” function is not implemented in the base class - must implement in derived class  Syntax: append " = 0 " to base method declaration class Widget { public: virtual void draw( Screen& theScreen ) = 0; };

CSC 143N 26 Pure Virtual Functions (2)  Compiler guarantees that class with pure virtual functions cannot be instantiated  If you call a pure virtual function, you’ll use the version from some derived class Widget *w = new Button(); w->draw( myScreen );