Inheritance CSC 123 Fall 2018 Howard Rosenthal

Similar documents
Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Reviewing Java Implementation Of OO Principles CSC Spring 2019 Howard Rosenthal

Java Object Oriented Design. CSC207 Fall 2014

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Inheritance -- Introduction

Interfaces CSC 123 Fall 2018 Howard Rosenthal

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal

CS-202 Introduction to Object Oriented Programming

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Chapter 6 Introduction to Defining Classes

Programming II (CS300)

Inheritance and Polymorphism

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Chapter 5 Object-Oriented Programming

Polymorphism and Inheritance

Chapter 7. Inheritance

Data Structures (list, dictionary, tuples, sets, strings)

Inheritance. Transitivity

Programming II (CS300)

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

PROGRAMMING LANGUAGE 2

What is Inheritance?

Chapter 10 Classes Continued. Fundamentals of Java

ITI Introduction to Computing II

Computer Science II (20073) Week 1: Review and Inheritance

9/10/2018 Programming Data Structures Inheritance

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Inheritance and Polymorphism

Lecture 18 CSE11 Fall 2013 Inheritance

ITI Introduction to Computing II

BBM 102 Introduction to Programming II Spring Inheritance

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CS 251 Intermediate Programming Inheritance

Inheritance, Polymorphism, and Interfaces

Chapter 6 Reflection

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Programming Exercise 14: Inheritance and Polymorphism

ENCAPSULATION AND POLYMORPHISM

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

3. Can an abstract class include both abstract methods and non-abstract methods? D

C++ Important Questions with Answers

ECE 122. Engineering Problem Solving with Java

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Comp 249 Programming Methodology

Chapter 4 Defining Classes I

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Chapter 15: Object Oriented Programming

CLASSES AND OBJECTS IN JAVA

Inheritance and Interfaces

8. Polymorphism and Inheritance

CS313D: ADVANCED PROGRAMMING LANGUAGE

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

INHERITANCE AND EXTENDING CLASSES

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

CSC9T4: Object Modelling, principles of OO design and implementation

Handout 9 OO Inheritance.

CS313D: ADVANCED PROGRAMMING LANGUAGE

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Defining Classes and Methods

Inheritance (Part 2) Notes Chapter 6

Inheritance. A key OOP concept

Inheritance, and Polymorphism.

CS11 Introduction to C++ Fall Lecture 7

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

25. Generic Programming

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance and Encapsulation. Amit Gupta

COMP 110/L Lecture 19. Kyle Dewey

More On inheritance. What you can do in subclass regarding methods:

Object Oriented Programming. Java-Lecture 11 Polymorphism

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Inheritance and Polymorphism. CS180 Fall 2007

Java Fundamentals (II)

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

What are the characteristics of Object Oriented programming language?

Programming in C# Inheritance and Polymorphism

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Data Abstraction. Hwansoo Han

OVERRIDING. 7/11/2015 Budditha Hettige 82

INHERITANCE. Spring 2019

CompuScholar, Inc. 9th - 12th grades

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Computer Science 210: Data Structures

Chapter 10: Inheritance

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Introduction to Inheritance

Super-Classes and sub-classes

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Transcription:

Inheritance CSC 123 Fall 2018 Howard Rosenthal

Lesson Goals Defining what inheritance is and how it works Single Inheritance Is-a Relationship Class Hierarchies Syntax of Java Inheritance The super Reference Method Overriding Much of the information in this section is adapted from: http://www.programmedlessons.org/java9/index.html Java Illuminated 5 TH Edition, Anderson, Julie and Franceschi Herve, Jones and Bartlett, 2019 Starting Out With Objects From Control Structures Through Objects, Gaddis, Tony, Pearson Publishing, 2016 2

The Three Pillars Of Object Oriented Programming There are three basic concepts used in object-oriented Encapsulation the organizing of data and behavior into objects Inheritance and Polymorphism are described in this and subsequent sections. We will also discuss the use of Interfaces, which greatly enhance the concept of inheritance 3

What Is Inheritance? Object oriented languages have a feature called inheritance, that enables you to define new classes based upon an existing class. The new classes are similar to the existing class, but have additional member variables and methods. This makes programming easier because you can build upon an existing class instead of starting out from scratch. Inheritance is part of the reason for the enormous success of modern software. Programmers are able to build upon previous work and to continuously improve and upgrade existing software. 4

Why Inheritance? Before object oriented programming if you had the source code for a class, you could copy the code and change it to do what you wanted. This approach had two major problems: It was hard to stay organized. Say that you already have several dozen classes which you need to keep and that you need additional classes based on the original ones. Also, say that you need several classes based on the new classes. You will end up with dozens of source files which are all versions of other source files that have been changed in various ways. Now say that a bug has been found in one of the source files. Some source files based on it need fixing; others, perhaps not. Without careful planning you will end up with an disorganized, inconsistent, buggy mess. You needed to study the original code. Say that you have a complicated class that basically does what you want, but you need a small modification. If you edit the source code, even to make a small change, you risk breaking something. So you must study the original code to be sure that your changes are correct which may not be easy. 5

Basic Principles Of Inheritance A common form of reuse of classes is inheritance. We can organize classes into hierarchies of functionality. The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy. We derive a subclass, which inherits behavior and fields from the superclass. 6

Java and Inheritance The class that is used to define a new class is called a parent class (or superclass or base class.) The class based on the parent class is called a child class (or subclass or derived class.) In diagrams, the arrow points from the child to the parent. In Java, (unlike with humans) children inherit characteristics from just one parent. This is called single inheritance. Some languages allow a child to inherit from more than one parent. This is called multiple inheritance. With multiple inheritance, it is sometimes hard to tell which parent contributed what characteristics to the child (as with humans). Java avoids these problems by using single inheritance. 7

A Few Common Synonyms There are three sets of phrases for describing inheritance relationships: parent / child base class / derived class superclass / subclass Programmers use all three sets interchangeably. 8

Two Simple Questions (1) Can a parent class have more than one child class? Can a parent class inherit characteristics from its child class? 9

Two Simple Questions (2) Can a parent class have more than one child class? Yes, a parent can have any number of children. But child can have only one parent. Can a parent class inherit characteristics from its child class? No. Inheritance goes in only one direction. 10

Objects And Classes (1) The picture shows a parent class and a child class, and some objects that have been constructed from each. These objects are shown as rectangles. In the picture, "Joe's car," "Mary's Ford," and "Bob's Ford" represent objects. The cloudy classes represent designs, not objects. Objects are constructed as a program runs. An object is constructed by following a description in a class file that was created by compiling a Java source program. How many types of automobile are there in the diagram? How many automobile objects are there in the diagram? 11

Objects And Classes (2) How many types of automobile are there in the diagram? 2 How many automobile objects are there in the diagram? 3 12

Hierarchies (1) We can organize classes into hierarchies of functionality. The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy. We derive a subclass, which inherits behavior and fields from the superclass. 13

Hierarchies (2) This picture shows a hierarchy of classes. It shows that "Ford is-a automobile," "Nissan is-a automobile," and that "VW is-a automobile." It also shows that "Sentra is-a Nissan." In a hierarchy, each class has at most one parent but might have several children classes. The class at the top of the hierarchy has no parent. This class is called the root of the hierarchy. 14

Visualizing A Simple Hierarchy In UML In UML diagrams, arrows point from the subclass to the superclass. 15

Superclasses and Subclasses A superclass can have multiple subclasses. Subclasses can be superclasses of other subclasses. A subclass can inherit directly from only one superclass. All classes in Java inherit from the Object class (to be discussed later). A big advantage of inheritance is that we can write code that is common to multiple classes once and reuse it in subclasses. A subclass can define new instance variables and methods, some of which may override (hide) those of a superclass. 16

Specifying Inheritance The syntax for defining a subclass is to use the extends keyword in the class header, as in accessmodifier class SubclassName extends SuperclassName { // class definition new variables, constructors and other methods (new or overriding) } The superclass name specified after the extends keyword is called the direct superclass. As mentioned, a subclass can have many superclasses, but only one direct superclass. 17

A Simple Example With Inheritance Let s look at the following files: TestVideoStore.java, Video.java, Movie.java The class Movie is a subclass of Video. An object of type Movie has these members: member member member title length avail director rating tostring() inherited from Video inherited from Video inherited from Video defined in Movie defined in Movie inherited from Video gettitle() getlength() getavailabl e() getdirector () getrating() inherited from Video inherited from Video inherited from Video defined in Movie defined in Movie settitle() setlength() setavailable () inherited from Video inherited from Video inherited from Video 18

Using A Super Constructor (1) Look at he constructor for class Movie. The class definition for Video has a constructor that initializes the instance variables of Video objects. The class Movie has a constructor that initializes the instance variables of Movie objects. The statement super(ttl, lngth) invokes a constructor of the parent to initialize some variables of the child. There are two constructors in the parent. The one that is invoked is the one that matches the argument list in super(ttl, lngth). The next two statements initialize variables that only Movie has. Important Note: super() must be the first statement in the subclass's constructor. super() will be inserted into any constructor of the subclass as the first statement if you do not do not explicitly use a super constructor. If you have more than one constructor in the subclass you can use the super() with or without parameter as appropriate. 19

Using A Super Constructor (2) An example. If the code looks like this: public Movie( String ttl, int lngth, String dir, String rtng ) { settitle( ttl ); // initialize inherited variables setlength( lngth ); setavailable( true ); director = dir; // initialize Movie variables rating = rtng; } Then the following insert takes place: public Movie( String ttl, int lngth, String dir, String rtng ) { super(); // inserted by compiler: parent's no-argument constructor settitle( ttl ); // initialize inherited variables setlength( lngth ); setavailable( true ); director = dir; // initialize Movie variables rating = rtng; } Note: In our program the class definition for Video (the superclass) lacks a noargument constructor. The proposed constructor (above) calls for such a constructor so it would cause a syntax error. 20

A Few Notes About The Default Constructor The programmer can explicitly write a no-argument constructor for a class. If the programmer does not write any constructors for a class, then a no-argument constructor (called the default constructor) is automatically supplied. If the programmer writes even one constructor for a class then the default constructor is not automatically supplied. So: if you write a constructor for a class, then you must also write a no-argument constructor if one is expected. Look at Test2VideoStore.java 21

Inheritance Rules for Constructors 22

Overriding A Parent Method A child's method overrides a parent's method when it has the same signature as a parent method. Remember that the signature of a method is the name of the method and its parameter list. When overriding a method with the same signature you can change the return type under certain conditions. Overriding method can have different return type but this new type must be A non-primitive and A subclass of what base class s overridden method is returning (i.e. co-variant Return Type). Example if a reference to a Video is returned in the superclass a reference to a Movie can be returned in the subclass method that is overriding Now the parent has its method, and the child has its own method with the same signature. Now look at Test3VideoStore.java and Movie3.java to see the overriding of tostring() in Movie You can also incorporate super in the process to print out the common parts the same way. 23

Inheritance Rules For Overwritten Methods 24

private Variables and Methods In A Superclass Superclass members declared as private are not inherited, although they are part of the subclass. Thus, a title, length and avail instance variable is allocated to all Movie objects, but methods of the Movie class cannot directly access title, length or avail directly. To set or get the value of title, length or avail, the Movie methods must call the inherited getxxx methods, which are public methods. This simplifies maintenance because the Video class enforces the data validation rules for title, length or avail. 25

protected Variables and Methods In A Superclass protected members are inherited by subclasses (like public members), while still being hidden from client classes (like private members). This means that the variables and methods that are protect can be directly accessed Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass. Disadvantage: Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance. For that reason, we prefer to use private, rather than protected, for our instance variables. 26

A Few More Notes On protected Members Declaring fields as private preserves encapsulation. Subclass methods call superclass methods to set the values of the fields, and the superclass methods enforce the validation rules for the data. However, calling methods incurs processing overhead. Declaring fields as protected allows them to be accessed directly by subclass methods. Classes outside the hierarchy and package must use accessors and mutators for protected fields. Advantage: protected fields can be accessed directly by subclasses, so there is no method-invocation overhead. Disadvantage: Maintenance is complicated because the subclass also needs to enforce validation rules. Recommendation: Define protected fields only when high performance is necessary. Avoid directly setting the values of protected fields in the subclass. 27

Inheritance Rules For Classes and Subclasses 28

The Object Class All classes have a parent class (have a super class) except one. The class at the top of the Java class hierarchy is called Object. If a class definition does not extend a parent class then it automatically has Object as a parent class. If a class definition does extend a parent class, then if the parent class does not extend a parent it automatically has Object as a parent class. And so on. Ultimately all classes have Object as an ancestor. This means that all classes in Java share some common characteristics. Those characteristics are defined in Object. For example, all classes have a tostring() method because the class Object defines that method so all classes get it by inheritance. Of course, usually when you write a class you override the tostring() method. Constructors for our classes have not mentioned Object. According to the rule, the compiler automatically does this: public Video( String ttl, int lngth ) { super(); // use the super class's constuctor title = ttl; length = lngth; avail = true; } And Video automatically has what is in red done: class Video extends Object 29

The Java Hierarchy for Video 30

Programming Exercise 1 Extending A class (1) Extending the Game class Download the Game class from Lesson 12 Classwork and read its structure Create a subclass PCBasedGame Add three new instance values minimum megabytes of RAM required, minimum number of disk megabytes required, (both as type int), and required gigahertz speed of processor (as a double) Create accessors and mutators for each new instance variable Create an overriding tostring() method and equals() method equals method is true if each pair of instance variables are equal Write a PCBasedClient class with the main program that does the following Reads in the description, required RAM MBs, disk MBs and Gigahertz speed for a PCBasedGame object pcbg1. Create a pcbg1 object Use tostring to print out pcbg1 Reads in the description, required RAM MBs, disk MBs and Gigahertz speed for a PCBasedGame object pcbg2. Create a pcbg2 object Use tostring to print out pcbg2 Use equals to check equality between the two games Use accessors and mutators to set all pcbg2 instance variable values to pcbg1 values Now use equals again to check between the two games 31

Programming Exercise 1 Extending A class (2) Please enter the game description for game one: Monopoly Please enter the required RAM MBs and Disk Size MBs for game one as type int: 24 120 Please enter the required CPU speed in Gigahertz for game one as a double: 32.7 Game Description: Monopoly Minimum configuration: RAM: 24 MB; hard disk: 120 MB; CPU 32.70 GHZ Please enter the game description for game two: Scrabble Please enter the required RAM MBs and Disk Size MBs for game two as type int: 36 197 Please enter the required CPU speed in Gigahertz for game two as a double: 45.2 Game Description: Monopoly Minimum configuration: RAM: 24 MB; hard disk: 120 MB; CPU 32.70 GHZ pcbg1 and pcbg2 are not equal pcbg1 and pcbg2 are now equal 32