Inheritance (Part 2) 1. 2...KomondorBloodHound PureBreedMix Dog Object.

Slides:



Advertisements
Similar presentations
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Advertisements

Inheritance. Inheritance  New class (derived class) is created from another class (base class).  Ex. EmployeeEmployee  HourlyEmployee  SalariedEmployee.
Inheritance (Part 3) 1. Preconditions and Inheritance  precondition  what the method assumes to be true about the arguments passed to it  inheritance.
Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1.
Inheritance Inheritance Reserved word protected Reserved word super
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
1 Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding l Object:
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
What is inheritance? It is the ability to create a new class from an existing class.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Utilities (Part 2) Implementing static features 1.
Inheritance (Part 4) Abstract Classes 1.  sometimes you will find that you want the API for a base class to have a method that the base class cannot.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Inheritance Chapter 10 Programs built from objects/instances of classes An O.O. approach – build on earlier work. Use classes in library and ones you have.
Topic 4 Inheritance.
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
Static Attributes and Inheritance  static attributes behave the same as non-static attributes in inheritance  public and protected static attributes.
Inheritance Notes Chapter 6 1. Inheritance  you know a lot about an object by knowing its class  for example what is a Komondor? 2
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
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.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
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.
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)
Classes Revisited Chapter 8.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Important Annoucement 1  I messed up something in the last class  if a subclass overrides a method that throws an exception then it must either 1. throw.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
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.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Inheritance (Part 3) 1. Preconditions and Inheritance  precondition  what the method assumes to be true about the arguments passed to it  inheritance.
BY:- TOPS Technologies
Inheritance (Part 4) Abstract Classes.
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
CS 302 Week 11 Jim Williams, PhD.
Interfaces.
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Interfaces.
Inheritance, Polymorphism, and Interfaces. Oh My
Inheritance.
Chapter 11 Inheritance and Polymorphism Part 1
Summary.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Inheritance (Part 2) 1

2...KomondorBloodHound PureBreedMix Dog Object

3 Dog - size : int - energy : int + setSize() + setEnergy() + equals(Object) : boolean + hashCode() : int + toString() : String... Mix - breeds : ArrayList + equals(Object) : boolean + hashCode() : int + toString() : String...

4 Mix object Dog object Object object size1 energy10 breeds1000 Mix mutt = new Mix(1, 10); 1.Mix constructor starts running creates new Dog subobject by invoking the Dog constructor 2.Dog constructor starts running creates new Object subobject by (silently) invoking the Object constructor 3.Object constructor runs sets size and energy creates a new empty ArrayList and assigns it to breeds

Invoking the Superclass Ctor  why is the constructor call to the superclass needed?  because Mix is-a Dog and the Dog part of Mix needs to be constructed  similarly, the Object part of Dog needs to be constructed 5

Invoking the Superclass Ctor  a derived class can only call its own constructors or the constructors of its immediate superclass  Mix can call Mix constructors or Dog constructors  Mix cannot call the Object constructor  Object is not the immediate superclass of Mix  Mix cannot call PureBreed constructors  cannot call constructors across the inheritance hierarchy  PureBreed cannot call Komondor constructors  cannot call subclass constructors 6

Constructors & Overridable Methods  if a class is intended to be extended then its constructor must not call an overridable method  Java does not enforce this guideline  why?  recall that a derived class object has inside of it an object of the superclass  the superclass object is always constructed first, then the subclass constructor completes construction of the subclass object  the superclass constructor will call the overridden version of the method (the subclass version) even though the subclass object has not yet been constructed 7

Superclass Ctor & Overridable Method public class SuperDuper { public SuperDuper() { // call to an over-ridable method; bad this.overrideMe(); } public void overrideMe() { System.out.println("SuperDuper overrideMe"); } 8

Subclass Overrides Method public class SubbyDubby extends SuperDuper { private final Date date; public SubbyDubby() { super(); this.date = new Date(); public void overrideMe() { System.out.print("SubbyDubby overrideMe : "); System.out.println( this.date ); } public static void main(String[] args) { SubbyDubby sub = new SubbyDubby(); sub.overrideMe(); } } 9

 the programmer's intent was probably to have the program print: SuperDuper overrideMe SubbyDubby overrideMe : or, if the call to the overridden method was intentional SubbyDubby overrideMe :  but the program prints: SubbyDubby overrideMe : null SubbyDubby overrideMe : 10 final attribute in two different states!

What's Going On? 1. new SubbyDubby() calls the SubbyDubby constructor 2. the SubbyDubby constructor calls the SuperDuper constructor 3. the SuperDuper constructor calls the method overrideMe which is overridden by SubbyDubby 4. the SubbyDubby version of overrideMe prints the SubbyDubby date attribute which has not yet been assigned to by the SubbyDubby constructor (so date is null) 5. the SubbyDubby constructor assigns date 6. SubbyDubby overrideMe is called by the client 11

 remember to make sure that your base class constructors only call final methods or private methods  if a base class constructor calls an overridden method, the method will run in an unconstructed derived class 12

Other Methods  methods in a subclass will often need or want to call methods in the immediate superclass  a new method in the subclass can call any public or protected method in the superclass without using any special syntax  a subclass can override a public or protected method in the superclass by declaring a method that has the same signature as the one in the superclass  a subclass method that overrides a superclass method can call the overridden superclass method using the super keyword 13

Dog equals  we will assume that two Dog s are equal if their size and energy are the public boolean equals(Object obj) { boolean eq = false; if(obj != null && this.getClass() == obj.getClass()) { Dog other = (Dog) obj; eq = this.getSize() == other.getSize() && this.getEnergy() == other.getEnergy(); } return eq; } 14

Mix equals (version 1)  two Mix instances are equal if their Dog subobjects are equal and they have the same public boolean equals(Object obj) { // the hard way boolean eq = false; if(obj != null && this.getClass() == obj.getClass()) { Mix other = (Mix) obj; eq = this.getSize() == other.getSize() && this.getEnergy() == other.getEnergy() && this.breeds.size() == other.breeds.size() && this.breeds.containsAll(other.breeds); } return eq; } 15 subclass can call public method of the superclass

Mix equals (version 2)  two Mix instances are equal if their Dog subobjects are equal and they have the same breeds  Dog equals already tests if two Dog instances are equal  Mix equals can call Dog equals to test if the Dog subobjects are equal, and then test if the breeds are equal  also notice that Dog equals already checks that the Object argument is not null and that the classes are the same  Mix equals does not have to do these checks again 16

@Override public boolean equals(Object obj) { boolean eq = false; if(super.equals(obj)) { // the Dog subobjects are equal Mix other = (Mix) obj; eq = this.breeds.size() == other.breeds.size() && this.breeds.containsAll(other.breeds); } return eq; } 17 subclass method that overrides a superclass method can call the overridden superclass method

Dog public String toString() { String s = "size " + this.getSize() + "energy " + this.getEnergy(); return s; } 18

Mix public String toString() { StringBuffer b = new StringBuffer(); b.append(super.toString()); for(String s : this.breeds) b.append(" " + s); b.append(" mix"); return b.toString(); } 19

Dog hashCode // similar to code generated by public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.getEnergy(); result = prime * result + this.getSize(); return result; } 20

Mix hashCode // similar to code generated by public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + this.breeds.hashCode(); return result; } 21

Mix Memory Diagram Mix object size5 energy5 breeds1750 inherited from superclass private in superclass not accessible by name to Mix

Mix UML Diagram 23 Dog Mix 1 ArrayList breeds

Preconditions and Inheritance  precondition  what the method assumes to be true about the arguments passed to it  inheritance (is-a)  a subclass is supposed to be able to do everything its superclasses can do  how do they interact? 24

Strength of a Precondition  to strengthen a precondition means to make the precondition more restrictive // Dog setEnergy // 1. no precondition // 2. 1 <= energy // 3. 1 <= energy <= 10 public void setEnergy(int energy) {... } 25 weakest precondition strongest precondition

Preconditions on Overridden Methods  a subclass can change a precondition on a method but it must not strengthen the precondition  a subclass that strengthens a precondition is saying that it cannot do everything its superclass can do 26 // Dog setEnergy // assume non-final none public void setEnergy(int nrg) { //... } // Mix setEnergy // bad : strengthen precond. 1 <= nrg <= 10 public void setEnergy(int nrg) { if (nrg 10) { // throws exception } //... }

 client code written for Dog s now fails when given a Mix  remember: a subclass must be able to do everything its ancestor classes can do; otherwise, clients will be (unpleasantly) surprised 27 // client code that sets a Dog's energy to zero public void walk(Dog d) { d.setEnergy(0); }