Inheritance Chapter 8.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

Object Oriented Programming with Java
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
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.
Inheritance Writing and using Classes effectively.
OOP (Java): Inheritance/ OOP Objectives – –to introduce inheritance, superclasses, subclasses, polymorphic data structures, and wrapper.
Inheritance in collections Week Main concepts to be covered Inheritance in ArrayList objects Subtyping Substitution.
CS1054: Lecture 18 - Inheritance. The DoME example "Database of Multimedia Entertainment" stores details about CDs and videos –CD: title, artist, # tracks,
Objects First With Java A Practical Introduction Using BlueJ Improving structure with inheritance 2.0.
Improving structure with inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Improving structure with inheritance (Chapters 8 and 9)
Improving structure with inheritance
Improving structure with inheritance. 25/11/2004Lecture 7: Inheritance2 Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables.
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,
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
Inheritance Chapter 9.
CPSC150 Abstract Classes and Interfaces Chapter 10.
CPSC150 Interfaces Chapter CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
CPSC150 Abstract Classes Chapter 10. CPSC150 Directory Example (note: your assignment does not have all of this) DirectoryEntry name phone public void.
Abstract Classes and Interfaces
More about inheritance Exploring polymorphism 3.0.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Programming Fundamentals 2: Inheritance/ F II Objectives – –to introduce inheritance, superclasses, subclasses, polymorphic data structures,
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.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Software Development
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
Inheritance (Part 2) Notes Chapter KomondorBloodHound PureBreedMix Dog Object Dog extends Object PureBreed extends Dog Komondor extends PureBreed.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Comp1004: Inheritance I Super and Sub-classes. Coming up Inheritance and Code Duplication – Super and sub-classes – Inheritance hierarchies Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
29-July-2002cse Inheritance © 2002 University of Washington1 Inheritance CSE 142, Summer 2002 Computer Programming 1
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Peyman Dodangeh Sharif University of Technology Fall 2014.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Improving structure with inheritance 3.0. The media project stores details about CDs and DVDs –CD: title, artist, number of tracks, playing time, got-it,
Session 06: C# OOP-3 Inheritance and Polymorphism. Static and dynamic type of an object. FEN AK - IT: Softwarekonstruktion.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
1 COS 260 DAY 17 Tony Gauvin. 2 Agenda Questions? 7 th Mini quiz –Chapter 7 –Password “GoBengals” –40 min Assignment 4 posted –Due Nov 9 (one week) Capstone.
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.
1 COS 260 DAY 18 Tony Gauvin. 2 Agenda Questions? 7 th Mini quiz Graded –Good results 8 th Mini Quiz –Chap 8  Next class Assignment 4 Due Assignment.
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.
Coming up Which methods are where? – Overriding Calling super’s methods Coupling and cohesion.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables © 2017 Pearson Education,
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Coming up Inheritance – Code duplication – Super classes – Constructors Polymorphic collections – “Anywhere a super class is, a sub class can go” Casting.
9 Improving structure with inheritance
Interfaces and Inheritance
Lecture 19 - Inheritance (Contd).
More about inheritance
COS 260 DAY 18 Tony Gauvin.
Inheritance Inheritance is a fundamental Object Oriented concept
Object Oriented Programming
Objects First with Java
Comp1202: Inheritance I Super and Sub-classes.
Improving structure with inheritance
Chapter 11 Inheritance and Encapsulation and Polymorphism
Lecture 15 Inheritance.
Presentation transcript:

Inheritance Chapter 8

Inheritance Superclass subclass of Animal superclass of dog and cat

Superclass has its own fields and methods Subclass inherits all of superclass fields and methods and adds some of its own Subclass has its own fields and methods

Inheritance Advantages One superclass for lots of subclasses Saves code rewriting for client Save code rewriting within class Note: There does not have to be an object of a superclass – there are no “animal” objects, but there may be: (triangle, isosceles triangle, right angle isosceles triangle).

Shapes Example Circle has: Triangle has: Make a parent: Shape color, xPosition, yPosition, Diameter Triangle has: color, xPosition, yPosition, length, height Make a parent: Shape

Subtyping Shape s1 = new Shape(); // ok Circle c = new Circle(); // ok Triangle t = new Triangle(); // ok Shape s2 = new Circle(); //ok.all circles are shapes Circle c2 = new Shape(); // NOT ok. not all shapes // are circles --------- c.findCircumference ( ); // ok if method exists s2.findCircumference( ); // NOT ok (Circle)s2.findCircumference(); // ok s2 is a Circle LHS must be same level or higher than RHS object must be same level or lower than method

Polymorphic variables Object variables in Java are polymorphic. (They can hold objects of more than one type.) They can hold objects of the declared type, or of subtypes of the declared type. Shape s1; s1 = new Shape(); s1 = new Circle(); s1 = new Triangle(); s1 is three different types (in the same program), s1 is polymorphic.

Polymorphism: assignment a = b; // all b are a b must be able to "fit into"/be lower than/be a subclass of a b IS-A a (note: backwards of assignment order) does NOT work for a IS-A b (same order as assignment)

Polymorphism: objects & methods obj.method( ) method must be in obj class or obj must be cast to the class where method appears obj can be cast to a LOWER class (subclass), but will get a run-time error if obj is NOT the subclass If method is an super class, ok without casting. that's the point of inheritance.

Practice Dog d = new Mammal(); Mammal m = new Dog( ); private final int nbrlegs = 4; private final stuff covering = FUR; ----------- Mammal() { // constructor} FeedsYoung() { nurses();} GivesBirth() { liveyoung(); } Practice Dog d = new Mammal(); Mammal m = new Dog( ); StBernard s = new Dog(); m.FeedsYoung( ); d.slobbers(); s.wagstail(); s.FeedsYoung(); Dog // fields for dogs ------- Dog() {// constructor } public void wagstail() { } StBernard // fields for St. Bernards ------ StBernard { /* constructor*/} public void slobbers() { }

Practice 8.11: Assume we have 4 classes: Person, Teacher, Student and PhDStudent. Teacher and Student are both subclasses of Person. PhDStudent is a subclass of Student. Which of the following are legal and why? Person p1 = new Student( ); Person p2 = new PhDStudent( ); PhDStudent phd1 = new Student ( ); Teacher t1 = new Person( ); Student s1 = new PhDStudent( ); s1 = p1; s1 = p2; p1 = s1; t1 = s1; s1 = phd1; phd1 = s1;

Practice 2 8.17 Look at the code below. You have four classes (O, X, T and M) and a variable of each of these. O o; X x; T t; M m; The following assignments are all legal: m = t; m = x; o = t; The following assignment are all illegal: o = m; o = x; x = o; What can you say about the relationships of these classes?

Inheritance code for Shape parent classes are no different from any classes we have written. public class Shape { private String color; private int xPosition; private int yPosition; Shapes() // constructor { // do something constructor-like } // methods

Inheritance code for Circle inheritance is implemented with “extends” Inheritance code for Circle public class Circle extends Shape { private int diameter; Circle() super(); // Shapes ctor // more constructor stuff } // other Circle methods Must call parent constructor as first line of subclass constructor

Superclass constructor call Subclass constructors must always contain a 'super' call. If none is written, the compiler inserts one (without parameters) works only, if the superclass has a constructor without parameters Must be the first statement in the subclass constructor.

arrow with open head means inherits from Shapes arrow with open head means inherits from Don't try this at home: Shapes inheritance is natural, but doesn't work well with what we know now. Problem: Circle cannot access private fields of Shape (like xPosition), so cannot draw itself. But Shape doesn't know enough about Circles to draw it. So, draw() can’t be in Circle or Shape, so circles can't be drawn. One solution is to make some parts protected (Chapter 9) or make Shapes an abstract class (Chapter 10).

Inheritance: what do we know? extends // used in subclass superclass has no indication inheritance is being used super() // calls constructor of superclass must be first statement of subclass

Book Example: DoME "Database of Multimedia Entertainment" stores details about CDs and videos CD: title, artist, # tracks, playing time, got-it, comment Video: title, director, playing time, got-it, comment allows (later) to search for information or print lists database to store details of all CDs and videos I know This and the next 10 slides are from OBWJ instructor web page.

DoME objects one object per CD or video; each object stores details for one item.

DoME classes add the obvious methods (getters and setters); not complete here - just examples add a print method to print out the details

Using inheritance solution: inheritance. make superclass with common attributes, make subclasses

Subclasses public class CD extends Item { private String artist; private int numberOfTracks; // constructors and methods omitted. } we add subclass fields; inherit superclass fields (note extends keyword) subclass objects will have all fields. public class Video extends Item { private String director; // constructors and methods omitted. }

Superclass: Item public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; /** * Initialise the fields of the item. */ public Item(String theTitle, int time) title = theTitle; playingTime = time; gotIt = false; comment = ""; } // methods omitted Superclass: Item how do we initialise the fields? superclass: nothing unusual.

Inheritance and constructors public class CD extends Item { private String artist; private int numberOfTracks; /** * Constructor for objects of class CD */ public CD(String theTitle, String theArtist, int tracks, int time) super(theTitle, time); artist = theArtist; numberOfTracks = tracks; } // methods omitted subclass: must call superclass constructor! Must take values for all fields that we want to initialise.

Database source code Advantage: Uses Item, not CD or Video public class Database { private ArrayList items; /** * Construct an empty Database. */ public Database() items = new ArrayList(); } * Add an item to the database. public void addItem(Item theItem) items.add(theItem); ... Taakes Advantage: Uses Item, not CD or Video note: code duplication in class Database removed as well! only on field, one ArrayList creation, on add method otherwise would have one addItem for CDs, one for videos (that's how original is)

Subtyping and parameter passing public class Database { public void addItem(Item theItem) ... } Video video = new Video(...); CD cd = new CD(...); database.addItem(video); database.addItem(cd); subclass objects may be passed to superclass parameters

Object diagram database object will hold two collections: one for CDs, one for videos

Class diagram without inheritance class diagram is simple (ArrayList not shown in BlueJ)

Class diagram with inheritance Much cleaner. subtyping takes care of different types. class diagram is simple (ArrayList not shown in BlueJ)

Polymorphic variables Object variables in Java are polymorphic. (They can hold objects of more than one type.) They can hold objects of the declared type, or of subtypes of the declared type. Big advantage in many applications

Polymorphic collections All (pre-Java 5)collections are polymorphic. The elements are of type Object. public void add(Object element) public Object get(int index)