Inheritance Like father like son Image from:

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
© 2006 Pearson Addison-Wesley. All rights reserved Inheritance When one class inherits another class, the new class becomes a specialized version.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
“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.
Intro to OOP with Java, C. Thomas Wu
© 2006 Pearson Addison-Wesley. All rights reserved Inheritance Systems Merchandise ElectronicsClothing TelevisionCamcorderShirtDressShoe DigitalAnalog.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Structured Programming Good for programming in the small Often doesn't scale up Limitations –Changes at top may affect lower-level algorithms –Code reuse.
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.
Inheritance. What Is Inheritance? Familiar examples: –A family tree (individuals inherit characteristics from other individuals) –A taxonomy (classes.
EVENTS Wiring together objects, code, and actions.
Topic 4 Inheritance.
Outline Creating Subclasses Overriding Methods Class Hierarchies Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright ©
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
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.
1 Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called the parent class, or.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 7.
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,
Example of Aggregation 1) aggregation - the class contains other structure(s) 2) specialization - the new class is a special case of the data structure.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
CS1020 Lecture Note #7: Object Oriented Programming Inheritance Like father, like son.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
public class Doubler extends Base {
Phil Tayco Slide version 1.1 Created Oct 30, 2017
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Overloading and Constructors
Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism Part 1
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

Inheritance Like father like son Image from:

2 Inheritance  Sometimes classes have commonalities  Consider a checking/savings/cd account  Consider a janitor/sales clerk/manager  Inheritance is a way of writing common code once, and using it in many classes  Commonalities are captured in a super-class  Also known as a base class or parent class  Differences are captured in sub-classes  Also known as a child class Image from:

3 Inheritance  Software reuse is at the heart of inheritance  The sub-class class inherits all properties of the parent  all methods  all variables  Inheritance relationships can be depicted in a UML class diagram  boxes represent classes  lines represent relationships between classes  an arrow with an open arrowhead pointing to the parent class indicates inheritance

4 Inheritance Inheritance creates an is-a relationship The child is a more specific kind of the parent Vehicle Car class Car extends Vehicle { // more data and methods } class Vehicle { // data and methods } UML Diagram indicating inheritance Java code indicating inheritance Motorcycle class Motorcycle extends Vehicle { // more data and methods }

5 Inheritance  Syntax: public class SubClass extends SuperClass { // data and methods } Read “SubClass is a specialized version of SuperClass” All Oval’s have width and height Circle is a specialized oval since the width and height are always the same.

6 Class Hierarchies  A child class of one parent can be the parent of another child, forming a class hierarchy Business WebBasedMaAndPa ServiceBusiness HomeBasedService RetailBusiness

7 The super Reference  Constructors are NOT inherited  A child’s constructor is responsible for calling the parent’s constructor  The word super  can be used as a method to mean “the parent classes constructor”  can be used as a direct reference to the super class  The first line of a child’s constructor should use the super reference to call the parent’s constructor

8 The super Reference class Account { protected double balance; Account(double openingBalance) { balance = openingBalance; } class MoneyMarketAccount extends Account { protected double annualInterestRate; MoneyMarketAccount(double openingBalance, double rate) { balance = openingBalance; // could you do this annualInterestRate = rate; // could you do this? } image from

9 The super Reference class Account { protected double balance; Account(double openingBalance) { balance = openingBalance; } class MoneyMarketAccount extends Account { protected double annualInterestRate; MoneyMarketAccount(double openingBalance, double rate) { super(openingBalance); // should do this annualInterestRate = rate; // should do this } image from img/superman.gif

10 import java.awt.Color; public class RedDot extends Oval { public RedDot( int x, int y, int d ) { super(x, y, d, d); setBackground( Color.red ); } public void flatten() { setSize(getWidth()+1, getHeight()-1); repaint(); } // assume a Jframe named window RedDot dotty = new RedDot(10, 20, 5); window.add(dotty,0); dotty.repaint(); dotty.setLocation(20, 30); dotty.flatten(); Oval +void setLocation(int, int) +void setSize(int, int) +void setBackground(Color) +int getX() +int getY() +Color getBackground() +Oval(int, int, int, int) RedDot +RedDot(int,int,int) +void flatten() Example

11 Conformance  When performing assignment “x = y;”  Y must conform to X  If X and Y are primitives then the type of y must  be the identical to the type of X  OR widen to the type of X  Otherwise  The class of Y must be identical to the class of X  OR the class of Y must be a subclass of X

12 Overriding Methods  A method in a super-class can be overridden in a sub-class.  The sub-class method must have exactly the same signature  same access, return type, name, formal parameter list  The sub-classes method is able to re-define the behavior of the super-class method

Overriding 13 Oval +setSize(int w, int h) … Target +setSize(int w, int h) … Oval s1 = new Oval(x,y,w,h); … s1.setSize(30, 30); Oval s1 = new Oval(x,y,w,h); … s1.setSize(30, 30); Target t1 = new Oval(x,y,w,h); … t1.setSize(30, 30); Target t1 = new Oval(x,y,w,h); … t1.setSize(30, 30);

14 Dynamic Dispatch  Mechanism used to determine which method to actually call  Determined at run time  The class of the actual calling object is determined  If that class contains the specified method, then execute it, otherwise look in the super-class for the method. Repeat if needed!

15 Overriding Example 1 class A { int i, j; A(int a, int b) { i = a; j = b; } void show() { System.out.println(“i and j: “ + i + “,” + j); } class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { System.out.println(“k: “ + k); } class Example { public static void main(String[] args) { B aBThing = new B(1,2,3); aBThing.show(); }

Consider A +A() +void jabberwock() C +C() +void jabberwock() B +B() +void jabberwock() D +D() +void jabberwock() public void foo(A jubJub) { jubJub.jabberwock(); } … foo(new A()); // OK? foo(new B()); // OK? foo(new C()); // OK? foo(new D()); // OK? public void foo(A jubJub) { jubJub.jabberwock(); } … foo(new A()); // OK? foo(new B()); // OK? foo(new C()); // OK? foo(new D()); // OK? Compile time: an object is treated as it’s declared type. Compiler ensures that the runtime code will work – not what the runtime code exactly means! Runtime: an object is treated according to it’s actual (most specific) type! Compile time: an object is treated as it’s declared type. Compiler ensures that the runtime code will work – not what the runtime code exactly means! Runtime: an object is treated according to it’s actual (most specific) type!

17 Overriding Example 2 class A { public void foo() { System.out.println(“inside foo A”); } class B extends A { public void foo() { System.out.println(“inside foo B”); } class C extends B { public void foo() { System.out.println(“inside foo C”); } class Demo { public static void main(String[] args) { A a = new A(); B b = new B(); C c = new C(); A reference; reference = a; reference.foo(); reference = b; reference.foo(); reference = c; reference.foo(); }

18 public class BasicCheckbook { protected int balance; // in cents /* postcondition balance == bd*100 + bc */ public BasicCheckbook(int bd, int bc) { balance = bd*100 + bc; } /* postcondition balance == old balance + dd*100 + dc */ public void deposit(int dd, int dc) { balance = balance + dd*100 + dc; } /* postcondition balance == old balance - (wd*100 + wc) */ public void withdraw(int wd, int wc) { balance = balance - (wd*100 + wc); } /* postcondition result == balance */ public int balanceInCents() { return balance; } BasicCheckbook # balance : int «constructor» + BasicCheckbook( int, int) «update» + deposit( int, int) + withdraw( int, int) «query» + balanceInCents() : int Image from:

19 public class CheckbookWithStrBalance extends BasicCheckbook { public CheckbookWithStrBalance(int bd, int bc) { super(bd, bc); } public String toString() { String dollarStr, centStr; int cents; dollarStr = "" + (balance / 100); cents = balance % 100; if (cents < 10) { centStr = "0" + cents; } else { centStr = "" + cents; } return "$" + dollarStr + "." + centStr; } BasicCheckbook # balance : int «constructor» + BasicCheckbook( int, int) «update» + deposit( int, int) + withdraw( int, int) «query» + int balanceInCents() CheckbookWithStrBalance «constructor» + CheckbookWithStr...( int, int) «query» + String toString()

20 public class CheckbookWithTotals extends CheckbookWithStrBalance { protected int depositTot, withdrawTot; public CheckbookWithTotals(int bd, int bc) { super(bd, bc); depositTot = 0; withdrawTot = 0; } public void deposit(int dd, int dc) { super.deposit(dd, dc); depositTot = depositTot + dd*100 + dc; } public void withdraw(int wd, int wc) { super.withdraw(wd, wc); withdrawTot = withdrawTot - (wd*100 + wc); } public int deposits() { return depositTot; } public int withdraws() { return withdrawTot; } BasicCheckbook # int balance «constructor» + BasicCheckbook( int, int) «update» + deposit( int, int) + withdraw( int, int) «query» + int balanceInCents() CheckbookWithStrBalance «constructor» + CheckbookWith...( int, int) «query» + String toString() CheckbookWithTotals # int depositTot # int withdrawTot «constructor» + CheckbookWithTotals( int, int) «update» + deposit( int, int) + withdraw( int, int) «query» + int deposits() + int withdraws()

21 Permit overdraft (negative balance) (charge $10 for each transaction in the red)

22 public class CheckbookWithRedInk extends CheckbookWithTotals { public CheckbookWithRedInk(int bd, int bc) { super(bd, bc); } public void deposit(int dd, int dc) { super.deposit(dd, dc); if (dd*100+dc < 0 && balance < 0) { System.out.println("$10 surcharge"); balance = balance ; } public void withdraw(int wd, int wc) { super.withdraw(wd.wc); if (wd*100+wc > 0 && balance < 0) { System.out.println("$10 surcharge"); balance = balance ; } public String toString() { String str; if (balance > 0) { str = super.toString(); } else { balance = -balance; str = "(" + super.toString() + ")"; balance = -balance; } return str; } BasicCheckbook # int balance «constructor» + BasicCheckbook( int, int) «update» + deposit( int, int) + withdraw( int, int) «query» + int balanceInCents() CheckbookWithStrBalance «constructor» + CheckbookWith...( int, int) «query» + String toString() CheckbookWithTotals # int depositTot # int withdrawTot «constructor» + CheckbookWithTotals( int, int) «update» + deposit( int, int) + withdraw( int, int) «query» + int deposits() + int withdraws()

23 public class Director { private CheckbookWithRedInk checkbook; public Director() { checkbook = new CheckbookWithRedInk( 100, 0 ); checkbook.deposit( 20, 0 ); checkbook.withdraw( 125, 99 ); System.out.println("Final Balance: " + checkbook.toString()); } CheckbookWithRedInk # int balance # int depositTot # int withdrawTot «constructor» + CheckbookWithRedInk( int, int) «update» + deposit( int, int) + withdraw( int, int) «query» + int balanceInCents() + String toString() + int deposits() + int withdraws() A flattened version of the class A client

24 Container  This class is meant to be extended to create customized components  Probably want to override setSize for example  Probably don’t need to override getX, getY, setLocation, getWidth, getHeight  Example: write a TrafficLight class!  Lights are centered horizontally and distributed vertically  Lights are 3/4 of the width of the light and ¼ of the light height

Object  All classes descend from Object  Two methods that should often be overridden Object +boolean equals(Object other) +String toString() …others not shown boolean equals(Object other) : returns true if the calling object is equal to the other one and false otherwise String toString() : returns the textual representation of the calling object

Fraction Class  Write a Fraction class  Represents a fraction (i.e. numerator / denominator)  Support addition and multiplication  Support equality checking and conversion to text Fraction +Fraction() +Fraction(int n,int d) +String toString() +boolean equals(Object other) +Fraction add(Fraction other) +Fraction multiply(Fraction other) // Code fragment showing usage Fraction f1 = new Fraction(3,5); Fraction f2 = new Fraction(6,3); Fraction f3 = f1.add(f2); Fraction f4 = f1.multiply(f2); System.out.println(f4.toString()); System.out.println(f4.equals(f3)); // Code fragment showing usage Fraction f1 = new Fraction(3,5); Fraction f2 = new Fraction(6,3); Fraction f3 = f1.add(f2); Fraction f4 = f1.multiply(f2); System.out.println(f4.toString()); System.out.println(f4.equals(f3));

Fraction class public class Fraction { private int num, denom; public Fraction(int n, int d) { … } public Fraction() { … } public Fraction multiply(Fraction other) { … } public Fraction add(Fraction other) { … } public String toString() { …} public boolean equals(Object other) { … } } public class Fraction { private int num, denom; public Fraction(int n, int d) { … } public Fraction() { … } public Fraction multiply(Fraction other) { … } public Fraction add(Fraction other) { … } public String toString() { …} public boolean equals(Object other) { … } }  What does a Fraction object look like textually?  When are two Fraction objects the same?

Equality  Equality can be defined in two ways  Identity equality: two objects are equal iff they are the same object  Content equality: two objects are equal if they have the same content  Both definitions are supported in Java  ==: this operator always means identity equality. Can be applied to objects.  equals method: this method usually means content equality but is defined as identity equality by default. Fraction f1 = new Fraction(3,5); Fraction f2 = new Fraction(3,5); Fraction f3 = new Fraction(5,3); boolean b1 = f1 == f2; boolean b2 = f1 == f3; boolean b3 = f1.equals(f2); boolean b4 = f1.equals(f3); Fraction f1 = new Fraction(3,5); Fraction f2 = new Fraction(3,5); Fraction f3 = new Fraction(5,3); boolean b1 = f1 == f2; boolean b2 = f1 == f3; boolean b3 = f1.equals(f2); boolean b4 = f1.equals(f3);

Summary  Most classes should override toString and equals  The equals method allows a class to define what equality means  The toString method allows a class to define it’s textual look.