David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 12: Subtyping and Inheritance.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Advertisements

Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Programming Languages Marjan Sirjani 2 2. Language Design Issues Design to Run efficiently : early languages Easy to write correctly : new languages.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
The Object Oriented Programming Languages (OOPL). Done by: Tayeb El Alaoui Supervised by: Dr Driss Kettani.
1 Introduction to CS Agenda Syllabus Schedule Lecture: the management of complexity.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Yixin Sun Class 17: Concurrency and OOP Fall 2010 UVa David Evans cs2220: Engineering Software.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Cs2220: Engineering Software Class 11: Subtyping and Inheritance Fall 2010 University of Virginia David Evans.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Adapted from Prof. Necula UCB CS 1641 Overview of COOL ICOM 4029 Lecture 2 ICOM 4029 Fall 2008.
Class 30: Language Construction cs1120 Fall 2009 David Evans.
Cs205: engineering software university of virginia fall 2006 Data Abstraction David Evans
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
CS 106 Introduction to Computer Science I 03 / 19 / 2007 Instructor: Michael Eckmann.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 12: Subtyping Rules What’s the.
David Evans CS200: Computer Science University of Virginia Computer Science Lecture 20: Objects I invented the term Object-
Types in programming languages1 What are types, and why do we need them?
David Evans CS655: Programming Languages University of Virginia Computer Science Lecture 17: Inheritance & Behavioral.
Cs205: engineering software university of virginia fall 2006 Introducing Java David Evans Don’t forget to your registration.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 14: Substitution Principle.
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
Salman Marvasti Sharif University of Technology Winter 2015.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 1: Introduction.
David Evans CS655: Programming Languages University of Virginia Computer Science Lecture 16: Smalltalking about Objects.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Cs205: engineering software university of virginia fall 2006 Subtyping and Inheritance David Evans Quiz Friday: classes through.
Principles of programming languages 10: Object oriented languages Isao Sasano Department of Information Science and Engineering.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
David Evans CS200: Computer Science University of Virginia Computer Science Lecture 22: Objects I invented the term Object-
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
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.
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 11: Subtyping and Inheritance.
David Evans CS150: Computer Science University of Virginia Computer Science Lecture 22: Objectifying Objects.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 7: A Tale of Two Graphs (and.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Cs205: engineering software university of virginia fall 2006 David Evans Object-Oriented Programming.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 12: Behavioral Subtyping.
Principles of programming languages 10: Object oriented languages
Modern Programming Tools And Techniques-I
Lecture 4: Type Systems.
Class 22: Inheritance CS150: Computer Science University of Virginia
Lecture 8: SmallTalking about Objects
Subtyping Rules David Evans cs205: engineering software BlackBear
PROGRAMMING PARADIGMS
Data Abstraction David Evans cs205: engineering software
Lecture 7: A Tale of Two Graphs CS201j: Engineering Software
Lecture 4: Data Abstraction CS201j: Engineering Software
Lecture 13: Subtyping Rules Killer Bear Climber
ICOM 4029 Fall 2003 Lecture 2 (Adapted from Prof. Necula UCB CS 164)
Presentation transcript:

David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 12: Subtyping and Inheritance

9 October 2003CS 201J Fall Menu Subtyping Inheritance What is Object-Oriented Programming

9 October 2003CS 201J Fall Subtyping Cell ConwayLifeCell ConwayLifeCell is a subtype of Cell Cell is a supertype of ConwayLifeCell ConwayLifeCell ≤ Cell

9 October 2003CS 201J Fall Inheritance To implement a subtype, it is often useful to use the implementation of its supertype This is also called “subclassing” In Java: class B extends A B is a subtype of A B inherits from A class C implements F C is a subtype of F both subtyping and inheritance just subtyping

9 October 2003CS 201J Fall Inheritance and Subtyping public class ExtremeLifeCell extends Cell { public CellState getNextState () // EFFECTS: Returns the next state for this cell. // The next state will be alive if this cell or any of its neighbors // is currently alive. { if (countAliveNeighbors () > 0) { return CellState.createAlive (); } else { return getState (); } ExtremeLifeCell is a subtype of Cell - anywhere a Cell is expected, we can use an ExtremeLifeCell ExtremeLifeCell inherits from Cell - the rep of an ExtremeLifeCell includes the rep of Cell - all public methods and constructors of Cell are also available for ExtremeLifeCell

9 October 2003CS 201J Fall Method Dispatch B is a subtype of A If both A and B have a method display which method should be called? A a = new A (); B b = new B (); a.display (); b.display (); a = b; a.display () Calls class A’s display method Calls class B’s display method

9 October 2003CS 201J Fall Dynamic Dispatch Search for the method up the type hierarchy, starting from the actual (dynamic) type of the object A B A a = new A (); B b = new B (); a.display (); b.display (); a apparent type actual type b apparent type actual type

9 October 2003CS 201J Fall Dynamic Dispatch Search for the method up the type hierarchy, starting from the actual (dynamic) type of the object A B A a = new A (); B b = new B (); a.display (); b.display (); a = b; a apparent type actual type b apparent type actual type Now: apparent type of a is A, actual type of a is B

9 October 2003CS 201J Fall public class Grid { Cell [][] cells; … public void step () // MODIFIES: this // EFFECTS: Executes one step for each cell in the grid. { CellState [][] nextStates = new CellState [rows][columns]; // Since we need to update all cells synchronously, we first calculate the next // state for each cell, and store it in a temporary array. Then, we update all cells. for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { nextStates [i][j] = cells[i][j].getNextState (); } } for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { cells[i][j].setState (nextStates[i][j]); } } } } } apparent type: Cell actual type: any subtype of Cell (could be ConwayLifeCell )

9 October 2003CS 201J Fall Apparent and Actual Types Apparent types are associated with declarations: they never change Actual types are associated with object: they are always a subtype of the apparent type Compiler does type checking using apparent type Virtual Machine does method dispatch using actual type

9 October 2003CS 201J Fall Downcasting java.util.Vector: public Object elementAt (int i); public class StringSet { Vector elements; public String choose () { String s = elements.elementAt (0); return s; } String s = (String) elements.elementAt (0); Casting changes the apparent type. The VM must check that the actual type is a subtype of the cast type.

9 October 2003CS 201J Fall Downcasting java.util.Vector: public Object elementAt (int i); public class StringSet { Vector elements; public String choose () { String s = elements.elementAt (0); return s; } String s = (String) elements.elementAt (0); Casting changes the apparent type. The VM must check that the actual type is a subtype of the cast type.

9 October 2003CS 201J Fall A Type Hierarchy Shape Quadrangle Triangle Rectangle Parallelogram Rhombus Square Equilateral EquilateralTriangle What are the subtypes of Parallelogram? What are the supertypes of Square?

9 October 2003CS 201J Fall A Class Hierarchy Shape Quadrangle Triangle Rectangle Parallelogram Rhombus Square Equilateral EquilateralTriangle

9 October 2003CS 201J Fall Reusing Implementations Shapes should have a setColor method Change Shape, Quadrangle, Parallelogram, Triangle, Equilateral, EquilateralTriangle, Rhombus, Rectangle, Square, etc. Change Shape others inherit new attribute and method automatically

9 October 2003CS 201J Fall Add isEquilateral method class Shape { public bool isEquilateral () { return false; } } class Equilateral { public bool isEquilateral () { return true; } }

9 October 2003CS 201J Fall Is a Rhombus equilateral? Shape Quadrangle Parallelogram Rhombus Equilateral isEquilateral? isEquilateral () { return false; } isEquilateral () { return true; } Inheritance can be tricky!

9 October 2003CS 201J Fall Solutions Java –Allow multiple supertypes using interfaces, but only one implementation –Pro: Safe and Simple, Con: Limits Reuse C++ –Allow it, let programmers shoot themselves if they want Eiffel –Explicit renaming or hiding (error if not done)

9 October 2003CS 201J Fall Java’s Solution: Interfaces Define a type with no implementation Classes can implement many interfaces: class B extends A implements I1, I2, I3 { … } means B is a subtype of A, I1, I2, and I3 B inherits the implementation of A

9 October 2003CS 201J Fall Example Interface public interface Comparable { int compareTo (Object o) { // EFFECTS: Compares this object with the specified // object for order. Returns a negative integer, zero, // or a positive integer as this object is less than, // equal to, or greater than the specified object. }

9 October 2003CS 201J Fall Java’s Sorting Routines public class java.util.Arrays { public static void sort (Object[] a, int fromIndex, int toIndex) // REQUIRES: All elements in a between // fromIndex and toIndex must // implement the Comparable interface. // EFFECTS: Sorts the elements of a between // fromIndex and toIndex into ascending // order, according to the natural ordering of // its elements (defined by compareTo).

9 October 2003CS 201J Fall PS3 sortonce implementation public class WordTally { private TallyRecord [] entries; private boolean isSorted; private int numEntries; public String getRankedWord(int n) { if (!isSorted) { java.util.Arrays.sort (entries, 0, numEntries); isSorted = true; } if (n <= numberOfWords()) { return entries[n-1].word; } else { return null; }

9 October 2003CS 201J Fall Implementing Comparable class TallyRecord implements Comparable { String word; int tally; tally > 0; public String p_word, int p_tally) p_tally > 0; { word = p_word; tally = p_tally; } public int compareTo (Object o) throws RuntimeException { if (o instanceof TallyRecord) { TallyRecord t2 = (TallyRecord) o; if (tally > t2.tally) { return -1; } else if (tally == t2.tally) { return word.compareTo (t2.word); } else { return 1; } } else { throw new RuntimeException ("Comparison to non-TallyRecord: " + o); }

9 October 2003CS 201J Fall Object- Oriented Programming

9 October 2003CS 201J Fall What is an Object? Packaging state and procedures –state: the rep What a thing is –procedures: methods and constructors What you can do with it

9 October 2003CS 201J Fall What is Object-Oriented Programming?

9 October 2003CS 201J Fall “Object-oriented programming is programming with inheritance. Data abstraction is programming using user-defined types. With few exceptions, object-oriented programming can and ought to be a superset of data abstraction. These techniques need proper support to be effective. Data abstraction primarily needs support in the form of language features and object-oriented programming needs further support from a programming environment. To be general purpose, a language supporting data abstraction or object-oriented programming must enable effective use of traditional hardware.” Bjarne Stroustrup’s Answer

9 October 2003CS 201J Fall “I invented the term Object-Oriented and I can tell you I did not have C++ in mind.” Alan Kay

9 October 2003CS 201J Fall Programming Language History Before 1954: twidling knobs, machine code, assembly code FORTRAN (John Backus, UVa dropout, 1954) – Formula Translation Algol (Peter Naur, Alan Perlis, et. al., ) –Most influential programming language –Many of the things Algol did first (types, while, blocks) are in Java

9 October 2003CS 201J Fall Programming Language History Simula (Dahl and Nygaard, ) –First language with subtyping and inheritance CLU (Liskov et. al., 1970s) –First language with good support for data abstraction (but no subtyping or inheritance) Smalltalk (Kay et. al., 1970s) –First successful language and programming system to support subtyping and inheritance

9 October 2003CS 201J Fall Object-Oriented Programming Object-Oriented Programming is a state of mind where you program by thinking about objects It is difficult to reach that state of mind if your language doesn’t have: –Mechanisms for packaging state and procedures Java has class –Subtyping Java has extends (subtype and subclass) and implements (subtype) Other things can help: dynamic dispatch, implementation inheritance, automatic memory management, mixins, good Indian food, Krispy Kremes, etc.

9 October 2003CS 201J Fall Who was the first object-oriented programmer?

9 October 2003CS 201J Fall By the word operation, we mean any process which alters the mutual relation of two or more things, be this relation of what kind it may. This is the most general definition, and would include all subjects in the universe. Again, it might act upon other things besides number, were objects found whose mutual fundamental relations could be expressed by those of the abstract science of operations, and which should be also susceptible of adaptations to the action of the operating notation and mechanism of the engine... Supposing, for instance, that the fundamental relations of pitched sounds in the science of harmony and of musical composition were susceptible of such expression and adaptations, the engine might compose elaborate and scientific pieces of music of any degree of complexity or extent. Ada, Countess of Lovelace, around 1830

9 October 2003CS 201J Fall Charge PS4 due Thursday, Oct 16 Exam 1 out Thursday, Oct 16 Exam review in section tomorrow –Bring your questions Next week: –When is it safe to say B is a subtype of A?