32
Inheritance CSC 123 Fall 2018 Howard Rosenthal

Lesson 12 - Inheritance CSC 123 Fall 2018...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

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lesson 12 - Inheritance CSC 123 Fall 2018...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

InheritanceCSC 123Fall 2018

Howard Rosenthal

Page 2: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

2

Much of the information in this section is adapted from:

http://www.programmedlessons.org/Java9/index.html

Java Illuminated 5TH Edition, Anderson, Julie and Franceschi Herve,

Jones and Bartlett, 2019

Starting Out With Objects From Control Structures Through Objects,

Gaddis, Tony, Pearson Publishing, 2016

Page 3: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 4: Lesson 12 - Inheritance CSC 123 Fall 2018...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 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

Page 5: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 6: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 7: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 8: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 9: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 10: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 11: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 12: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 13: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 14: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 15: Lesson 12 - Inheritance CSC 123 Fall 2018...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

Visualizing A Simple Hierarchy In UML

� In UML diagrams, arrows point from the subclass to the superclass.

15

Page 16: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 17: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 18: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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:

18

member member member

title inherited from Video getTitle() inherited

from Video setTitle() inherited from Video

length inherited from Video getLength() inherited

from Video setLength() inherited from Video

avail inherited from Video

getAvailable()

inherited from Video

setAvailable()

inherited from Video

director defined in Movie

getDirector()

defined in Movie

rating defined in Movie getRating() defined in

Movie

toString() inherited from Video

Page 19: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 20: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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 variablesrating = 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 constructorsetTitle( ttl ); // initialize inherited variables setLength( lngth ); setAvailable( true );director = dir; // initialize Movie variablesrating = rtng;

}

Note: In our program the class definition for Video (the superclass) lacks a no-argument constructor. The proposed constructor (above) calls for such a constructor so it would cause a syntax error.

20

Page 21: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 22: Lesson 12 - Inheritance CSC 123 Fall 2018...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

Inheritance Rules for Constructors

22

Page 23: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 24: Lesson 12 - Inheritance CSC 123 Fall 2018...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

Inheritance Rules For Overwritten Methods

24

Page 25: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 26: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 27: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 28: Lesson 12 - Inheritance CSC 123 Fall 2018...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

Inheritance Rules For Classes and Subclasses

28

Page 29: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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 constuctortitle = ttl; length = lngth; avail = true;

}� And Video automatically has what is in red done:

class Video extends Object 29

Page 30: Lesson 12 - Inheritance CSC 123 Fall 2018...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

The Java Hierarchy for Video

30

Page 31: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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

Page 32: Lesson 12 - Inheritance CSC 123 Fall 2018...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

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