Modeling with Inheritance

Slides:



Advertisements
Similar presentations
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Stéphane Ducasse 1 Design Points - Subclassing vs Subtyping Stéphane Ducasse
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
The child gets it all..  Factor out common behavior  parent class implements behavior needed by children  guarantee that all subclasses have the characteristics.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
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,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Object-Orientated Design and Programming Unit 9: Abstract Classes and Interfaces Jin Sa.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design Guidelines.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Peyman Dodangeh Sharif University of Technology Fall 2014.
COP INTERMEDIATE JAVA Data Structures. A data structure is a way of organizing a collection of data so that it can be manipulated effectively. A.
Chapter 8 Specialization aka Inheritance. 2 Inheritance  Review of class relationships  Uses – One class uses the services of another class, either.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Coming up: Inheritance
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
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.
C10, Mechanisms for Software Reuse. Substitutability A variable declared as one type holds a value of another type In Java either: Subclass: allPiles.
Object Oriented Programming in Java Habib Rostami Lecture 7.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
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.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
CSCI 62 Data Structures Dr. Joshua Stough September 23, 2008.
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Unified Modeling Language (UML)
Sections Inheritance and Abstract Classes
Double-Ended Queues Chapter 5.
Inheritance Class Hierarchies SoftUni Team Technical Trainers C# OOP
Marcus Biel, Software Craftsman
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Inheritance and Polymorphism
03/10/14 Inheritance-2.
Chapter 11 Object-Oriented Design
A tree set Our SearchTree class is essentially a set.
Advanced Programming in Java
Week 4 Object-Oriented Programming (1): Inheritance
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CSC 205 Java Programming II
MSIS 670 Object-Oriented Software Engineering
A tree set Our SearchTree class is essentially a set.
Advanced Programming Behnam Hatami Fall 2017.
Code reuse through subtyping
Review: Classes, Inheritance, and Collections
Recitation 7 October 7, 2011.
Collections Framework
Based on slides by Alyssa Harding & Marty Stepp
Delegation vs inheritance
Object-Oriented Programming
Chapter 8 Inheritance Part 2.
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Modeling with Inheritance James Brucker

Uses of Inheritance 1. Factor out common elements (code reuse) parent class implements behavior needed by children parent defines attributes for all classes avoids duplicate or inconsistent code. 2. Specialize child class can redefine behavior of the parent 3. Enable polymorphism

Benefits of Inheritance? 1. Reuse code 2. Define a family of related types (polymorphism)

When To Use Inheritance?

Liskov Substitution Principle In a program, if all objects of the superclass are replaced by objects from a subclass, the program should still work correctly. Example: 1. Scanner can read from an InputStream: s = new Scanner( InputStream ) 2. FileInputStream extends InputStream 3. Scanner should also work correctly using a FileInputStream, s = new Scanner( fileInputStream ) Scanner reads from InputStream FileInputStream

Liskov Principle example A method that is expecting an object of a ParentClass type should also work if invoked with an object from any subclass. public void doSomething( ParentClass obj ) should work with: 1. doSomething ( new ParentClass() ) 2. doSomething ( new Subclass() ) 3. doSomething (new SubSubSubclass() )

Substitution Principle (2) A Scanner can read from an InputStream InputStream input = System.in; // construct Scanner using InputStream Scanner scanner = new Scanner( input ); while( scanner.hasNext() ) { String w = scanner.next( ); System.out.print(w);

Substitution Principle (3) Substitute a FileInputStream for the InputStream. Scanner should still work! InputStream input = null; try { input = new FileInputStream( "/temp/sample.txt"); } catch ( FileNotFoundException e ) { } Scanner scanner = new Scanner( input ); while (scanner.hasNext()) { String w = scanner.next( ); System.out.print(w);

Specialization A subclass can override (redefine) a method inherited from the parent, in order to specialize the behavior. Subclass specializes the behavior for its own needs, but still conforms to contract of parent's behavior. public class Person { private String name; public String getName() { return name; } public String toString() { return name; } } public class Student extends Person { protected String studentId; // redefine toString() to include Student ID. public String toString() { return getName()+" ID: "+studentId;

Specialization shadows attributes If a child class defines an attribute with the same name as attribute of parent class, it creates a new attribute that "hides" the parent attribute. But the parent attribute is still there (in objects of child class)! This is called shadowing. Also called hiding. Use "super" to access parent's members. public class Person { protected long id; . . . } public class Student extends Person { private String id; // OK to define a new id! public String toString() { return "student id: "+ id +" citizen id: "+super.id;

Shadow Attributes In general, don't do it. Redefining an attribute (deliberately) is poor design. Better to fix the design. duplicating an inaccessible, private variable (by coincidence) is OK.

Extension A subclass can define new behavior that the superclass does not have. A subclass can also define new attributes. public class Person { private String name; public String toString() { return name; } } public class Student extends Person { protected List<Course> courses; // new attribute // new behavior public void addCourse(Course c) { . . . } public void getCredits( ) { // compute credits for all courses that // student got a passing grade.

Bad Example: violates "is a" rule A stack of objects is a simple data collection, like this... To store the data in the stack we could use a linked list... Stack + push( Object ) + pop( ) + peek( ) + isEmpty( ) LinkedList + addFirst( item ) + addLast( item ) + getFirst( ) + getLast( ) + get( index ) + remove( index )

Example: A Stack (2) LinkedList + addFirst( item ) + addLast( item ) + get( index ) + removeFirst( ) + removeLast( ) + isEmpty( ) . . . Can we define Stack as a subclass of LinkedList? All we need to do is add the 4 stack methods and we're done! class Stack extends LinkedList { public Stack() { super(); } public void push(Object o){ addFirst( o ); } public Object pop() { ` return removeFirst( ); public Object peek() { return get(0); Stack + push( Object ) + pop( ) + peek( ) + isEmpty( )

Example: A Stack (3) The problem with this is that Stack will exhibit all the behavior of a LinkedList, including methods that should not exist for a stack. /* Stack example */ public void stackTest( ) { Stack stack = new Stack( ); stack.push( "First item" ); stack.push( "Second item" ); stack.push( "Third item" ); stack.push( "Fourth item" ); // cheat! get the 3nd item String s = stack.get( 2 ); // cheat! add item at front of stack stack.addFirst( "Ha ha ha!"); Behavior inherited from ListedList

"is a" (kind of) relationship A simple test for whether inheritance is reasonable: Subclass is a Superclass CheckingAccount is a (kind of) BankAccount Number is an (kind of) Object Double is a (kind of) Number Rectangle is a 2-D Shape Rectangle extends Shape2D

"is a" test doesn't always work X A Square is a Rectangle but a rectangle can have length  width X ArrayList is a List List is a type (interface) not a class X A Freshman is a Student but next year she will be a sophomore. Use an attribute for features that change. X George Bush is a President an instance of a class, not a subclass Student Freshman

"a Stack has a LinkedList" Attribute: "has a" In the case of a Stack, we would say: "a Stack has a LinkedList" "has a" means that something should be an attribute "has a" indicates an association. UML uses an open arrowhead for association Stack - items : LinkedList + push( Object ) + pop( ) + peek( ) + isEmpty( ) LinkedList + addFirst( item ) + addLast( item ) + getFirst( ) + get( index ) + remove( index ) 1

Composition vs Inheritance "Favor composition over inheritance" (design principle) Consider using aggregation (has a ...) instead of inheritance (is a ...). Stack List List  Stack has a List X Stack is a List Stack

Java LinkedList is a Stack ! java.util.LinkedList provides the stack methods. You can use LinkedList as a Stack or Deque. Is this a good design? LinkedList<T> + addFirst( item ) + addLast( item ) + getFirst( ): T + get( index ): T + remove( index ) + isEmpty( ) + push( item ) + pop( ): T + peek( ): T Stack methods are defined in LinkedList

Problems with Inheritance Can only have one parent class Binds objects to one hierarchy (not flexible) Sometimes the parent class doesn't know how a behavior should be implemented Example: Shape is parent for Rectangle, Circle, ... what should Shape.draw( ) do?

Don't Overuse Inheritance... Don't use a subclass in situations where an object may need to change class during its life time. Example: Full-time and Part-time students have different requirements and behavior. Should we model this using inheritance? Student FullTimeStudent PartTimeStudent

Modeling a "role" or "status" A student can change from Full-time to Part-time. Full-time or part-time is a role or status. Model this using an attribute that refers to an object of the appropriate status. attendance PartTime FullTime Student Enrollment 1 *

Prefer attribute over inheritance For Freshman - Student example, model Freshman as an attribute... and assign behavior to it. Student - status + push( Object ) + pop( ) + peek( ) + isEmpty( ) <<interface>> EnrollmentYear + getEnrollment( ) + canEnroll( course ) 1 Freshman Senior

Don't Overuse Inheritance... Subclass doesn't add significant extension or specialization Example: a library has several types of recordings: Jazz Recording, Classical Recording, Pop Recording, ... Recordings may be Tape or CDROM Recording ClassicalRecording JazzRecording . . . PopRecording JazzCDROMRecording JazzTapeRecording

Use Interface to describe behavior "Set" is an interface because it doesn't implement any methods or provide any attributes. HashSet implements Set Set + add( item ) + clear( ) + isEmpty( ) + iterator( ) + size( ) + toArray( ) ... HashSet TreeSet . . .