Comp1202: Inheritance I Super and Sub-classes.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

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.
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
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,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance Chapter 8.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Abstract Classes and Interfaces
More about inheritance Exploring polymorphism 3.0.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Intro to OOP with Java, C. Thomas Wu
Programming Fundamentals 2: Inheritance/ F II Objectives – –the use of super, overriding, method polymorphism (dynamic binding), protected.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Programming Fundamentals 2: Inheritance/ F II Objectives – –to introduce inheritance, superclasses, subclasses, polymorphic data structures,
More about inheritance Exploring polymorphism 5.0.
Objects First With Java A Practical Introduction Using BlueJ Method overriding 2.0.
Comp1004: Inheritance I Super and Sub-classes. Coming up Inheritance and Code Duplication – Super and sub-classes – Inheritance hierarchies Inheritance.
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.
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.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
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.
Comp1004: Building Better Objects II Encapsulation and Constructors.
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.
Software Construction Lab 05 Abstraction, Inheritance, and Polymorphism in Java.
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 –
6.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables © 2017 Pearson Education,
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
Objects First with Java A Practical Introduction using BlueJ
More about inheritance
Objects First with Java A Practical Introduction using BlueJ
CSC 143 Inheritance.
Lecture 19 - Inheritance (Contd).
Java Programming Language
More about inheritance
Encapsulation and Constructors
COS 260 DAY 18 Tony Gauvin.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Java Programming
Java Inheritance.
Objects First with Java A Practical Introduction using BlueJ
Objects First with Java
Object-Oriented Programming
Java Programming Language
Objects First with Java A Practical Introduction using BlueJ
F II 8. More on Inheritance Objectives
Final and Abstract Classes
Improving structure with inheritance
Lecture 15 Inheritance.
Presentation transcript:

Comp1202: Inheritance I Super and Sub-classes

Coming up Inheritance and Code Duplication Super and sub-classes Inheritance hierarchies Inheritance and Encapsulation Constructors and super() Inheritance, References and Collections Substitution The Object Class Inheritance at the core of Java

Inheritance and Code Duplication

Duplication in Classes We have seen how duplicating code is bad It creates opportunities for errors (inconsistency) Is harder to maintain Makes code harder to read But consider properly encapsulated but similar classes (classes that are responsible for themselves, and hide methods via the protected keyword) They can’t share code with another class So do you have to duplicate it?

Example Think about music CDs and films on DVDs... What properties do they share? N.B. The following example is based on the the DOME project from the BlueJ book

Objects First with Java DoME classes N.B This is a simple form of class diagram The top half shows properties The bottom half shows methods add the obvious methods (getters and setters); not complete here - just examples add a print method to print out the details Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling

DVD Source Code public class DVD { private String title; private String director; private String comment; DVD(String theTitle, String theDirector) title = theTitle; director = theDirector; comment = " "; } void setComment(String newComment) { ... } String getComment() void print() ...

DVD Source Code CD Source Code public class CD public class DVD { { private String title; private String artist; private String comment; CD(String theTitle, String theArtist) title = theTitle; artist = theArtist; comment = " "; } void setComment(String newComment) { ... } String getComment() void print() ... public class DVD { private String title; private String director; private String comment; DVD(String theTitle, String theDirector) title = theTitle; director = theDirector; comment = " "; } void setComment(String newComment) { ... } String getComment() void print() ...

A kind of Code Duplication DVD Source Code CD Source Code public class CD { private String title; private String artist; private String comment; CD(String theTitle, String theArtist) title = theTitle; artist = theArtist; comment = " "; } void setComment(String newComment) { ... } String getComment() void print() ... public class DVD { private String title; private String director; private String comment; DVD(String theTitle, String theDirector) title = theTitle; director = theDirector; comment = " "; } void setComment(String newComment) { ... } String getComment() void print() ... A kind of Code Duplication

Code Duplication Bad Thing Even this code duplication is a: If you debug one bit of code in one class, you have to change each duplicated code fragment individually. This can take ages! If you have 150 classes with the same bit of code, it’s very easy to miss one...

Wouldn’t it be good... If a class could inherit some properties that it shares with other classes a bit like a common template shipping out common functionality and keeping the specific stuff in the class In Object Orientated programming, this is known as inheritance

Objects First with Java Using inheritance Any class that is inherited from is called a superclass Any class that inherits from another is called a subclass The sub-classes inherit all the properties and methods from the superclass solution: inheritance. make superclass with common attributes, make subclasses They can also add more of their own Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling

Inheritance hierarchies Objects First with Java Inheritance hierarchies Any subclass can also be a superclass This can create a tree of classes called an inheritance hierarchy inheritance hierarchies are nothing unusual. we see them all the time. (a masters student is a students is a person...) Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling

Inheritance hierarchies Objects First with Java Inheritance hierarchies Any subclass can also be a superclass This can create a tree of classes called an inheritance hierarchy N.B How class diagrams show inheritance (with the arrows pointing from sub-class to superclass) inheritance hierarchies are nothing unusual. we see them all the time. (a masters student is a students is a person...) Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling

Inheritance in Java You don’t need to add anything to the superclass public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; // constructors and methods omitted. } You don’t need to add anything to the superclass

Inheritance in Java You don’t need to add anything to the superclass public class CD extends Item { private String artist; private int numberOfTracks; // constructors and methods omitted. } You don’t need to add anything to the superclass You declare the inheritance in the sub-class using the extends keyword Q: What is the advantage of leaving the superclass unchanged? public class DVD extends Item { private String director; // constructors and methods omitted. }

Inheritance in Java You don’t need to add anything to the superclass public class CD extends Item { private String artist; private int numberOfTracks; // constructors and methods omitted. } You don’t need to add anything to the superclass You declare the inheritance in the sub-class using the extends keyword Q: What is the advantage of leaving the superclass unchanged? public class DVD extends Item { private String director; // constructors and methods omitted. } A: So you can inherit from any class – even those you didn’t create and/or can’t edit

Inheritance and Encapsulation

The Three Pillars of OOP Encapsulation Inheritance Polymorphism

Encapsulation and Inheritance Encapsulation is the principle that every class should be responsible for itself We enforce it using the public and private keywords But is the encapsulation within the class or within the whole inheritance hierarchy? In other words: Should sub-classes be able to see all the properties and methods in their super classes?

Encapsulation Expanded In fact Java uses several keywords for encapsulation Public Everyone can see it Protected Only this class, its sub-classes and the package can see it Default (no keyword) Only this class and the package can see it Private Only this class can see it

Encapsulation Expanded In fact Java uses several keywords for encapsulation Public Everyone can see it Protected Only this class, its sub-classes and the package can see it Default (no keyword) Only this class and the package can see it Private Only this class can see it Remember – Be Paranoid: assume everything should be private from the beginning

Encapsulation Expanded In fact Java uses several keywords for encapsulation Public Everyone can see it Protected Only this class, its sub-classes and the package can see it Default (no keyword) Only this class and the package can see it Private Only this class can see it Remember – Be Paranoid: assume everything should be private from the beginning Explicitly make public the methods (and sometime properties) you want other classes to use

Encapsulation Expanded In fact Java uses several keywords for encapsulation Public Everyone can see it Protected Only this class, its sub-classes and the package can see it Default (no keyword) Only this class and the package can see it Private Only this class can see it Remember – Be Paranoid: assume everything should be private from the beginning Explicitly make public the methods (and sometime properties) you want other classes to use Explicitly make protected any implementation details you think sub-classes may need access to

Encapsulation and Constructors Remember Constructors Special methods that initialise an object when you create it using the new keyword Constructors are important for encapsulation as a class should be in charge of initialising itself

So Are These Classes Encapsulated? public class Item { protected String title; protected int playingTime; protected boolean gotIt; protected String comment; public Item(String theTitle, int time) title = theTitle; playingTime = time; gotIt = false; comment = ""; } // methods omitted public class CD extends Item { protected String artist; protected int numberOfTracks; public CD( String theTitle, String theArtist, int tracks, int time) title = theTitle; playingTime = time; gotIt = false; comment = ""; artist = theArtist; numberOfTracks = tracks; } // methods omitted

So Are These Classes Encapsulated? public class Item { protected String title; protected int playingTime; protected boolean gotIt; protected String comment; public Item(String theTitle, int time) title = theTitle; playingTime = time; gotIt = false; comment = ""; } // methods omitted public class CD extends Item { protected String artist; protected int numberOfTracks; public CD( String theTitle, String theArtist, int tracks, int time) title = theTitle; playingTime = time; gotIt = false; comment = ""; artist = theArtist; numberOfTracks = tracks; } // methods omitted No. Because here CD is taking the responsibility for constructing properties defined in the Item class

Better to call the super-class constructor public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; public Item(String theTitle, int time) title = theTitle; playingTime = time; gotIt = false; comment = ""; } // methods omitted public class CD extends Item { private String artist; private int numberOfTracks; public CD( String theTitle, String theArtist, int tracks, int time) super(theTitle, time); artist = theArtist; numberOfTracks = tracks; } // methods omitted We can call the super-class’ constructor using the super keyword. Now we can make the properties private and we have proper encapsulation.

Superclass constructor rules In fact subclass constructors must always contain a 'super' call. If none is written, the compiler acts as if there is one (without parameters) works only if the superclass has a constructor without parameters Must be the first statement in the subclass constructor. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Inheritance, References and Collections

References and Inheritance Item item1 = new CD(“Nevermind”, “Nivana”, 11, 56); Item item2 = new DVD(“Gladiator”, “Ridley Scott”, 155); item1.print(); item2.print(); Will this code work?

References and Inheritance Item item1 = new CD(“Nevermind”, “Nivana”, 11, 56); Item item2 = new DVD(“Gladiator”, “Ridley Scott”, 155); item1.print(); item2.print(); Yes, this is called substitution. An Item reference can store any sub-class of Item

Collections and Inheritance ArrayList<Item> items; items = new ArrayList<Item>(); items.add( new CD(“Nevermind”, “Nivana”, 11, 56) ); items.add( new DVD(“Gladiator”, “Ridley Scott”, 155) ); for(Item i : items) { i.print(); } Yes, this is called substitution. An Item reference can store any sub-class of Item This is useful in collections. Because we can declare a collection of super-classes and can use it to store any type of sub-class

Collections and Inheritance ArrayList<Item> items; items = new ArrayList<Item>(); items.add( new CD(“Nevermind”, “Nivana”, 11, 56) ); items.add( new DVD(“Gladiator”, “Ridley Scott”, 155) ); for(Item i : items) { i.print(); int tracks = i.getNumberOfTracks(); System.out.println(tracks); } Yes, this is called substitution. An Item reference can store any sub-class of Item But will this work?

Collections and Inheritance ArrayList<Item> items; items = new ArrayList<Item>(); items.add( new CD(“Nevermind”, “Nivana”, 11, 56) ); items.add( new DVD(“Gladiator”, “Ridley Scott”, 155) ); for(Item i : items) { i.print(); int tracks = i.getNumberOfTracks(); System.out.println(tracks); } Yes, this is called substitution. An Item reference can store any sub-class of Item No, because once its stored in an Item reference java will forget if it’s a CD or a DVD. This wont compile as Item has a print method but not getNumberOfTracks

The Object Class

Inheritance is a Core Part of Java Where is the ‘default constructor’ defined? How about the .equals() method, it’s not a part of the String class How come we can pass any object to System.out.println() ? Where are these magical methods defined?

The Object Class All classes inherit from Object. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The Object Class You’ve been dabbling with inheritance the whole time You don’t need to extend the Object class (you can if you really want to) as every object extends the Object class (unless it extends something else) Look Object up in the API

Summary Inheritance and Code Duplication Inheritance and Encapsulation Super and sub-classes Inheritance hierarchies Inheritance and Encapsulation Constructors and super() Inheritance, References and Collections Substitution The Object Class Inheritance at the core of Java