Inheritance Inheritance is a fundamental object-oriented technique it enhances software design and...

Preview:

Citation preview

Inheritance Inheritance is a fundamental object-oriented technique

it enhances software design and promotes reuse

We will focus on: deriving new classes

creating class hierarchies

the protected modifier

polymorphism via inheritance1

The Three Pillars of OOP

Encapsulation

Inheritance

Polymorphism 

Every class in Java extends some other class.

2

Inheritance

If you don't explicitly specify the class that your new class extends

it automatically extend the class Object.

3

Encapsulation - By creating class e Student -

and storing in it all the variables and methods

associated with a student we are:

Encapulating in the Student class

All data pertaining to a student in one place

4

Class Hierarchy

Java uses a class hierarchy class hierarchy to organize its classes. All classes in Java exist in a class hierarchy

The Object class Object class forms the root of the hierarchy. forms the root of the hierarchy.

5

OBJECT CLASS

Some classes extend extend Object directlyObject directly,

while other classes are subclasses of Objectsubclasses of Object further down the hierarchy.

The Object class contains methods that are inherited by

all its child classes

6

Inheritance allows a software developer to derive a new class from an existing one

The existing class is called the parent class, or

superclass, or base class

The derived class The derived class is called the child class or subclass.

7

8

Object classObject class

Child classChild class

PARENTPARENT

Child Child

PARENT CHILD RELATIONSHIPPARENT CHILD RELATIONSHIP

UML OR Unified Modeling Language is used to model UML OR Unified Modeling Language is used to model an application’s structures, behavior and even business an application’s structures, behavior and even business

processesprocesses

Inheritance

The child inherits characteristics of the parent.

The child class inherits the methods and datamethods and data defined in the parent class

This means that all child classes have access to the methods and data.

9

Inheritance relationships are shown in a UML class diagram as solid arrow with an unfilled triangular arrowhead pointing to the parent class

10

Vehicle

Car

Inheritance creates an is-a relationship,

meaning the child is a more specific version of the parent

Class Car is a subclass of Vehicle and

It inherits state and behavior from its parent

An object’s object’s statestate is in the form of               instance variables   

 its behaviorbehavior in the form of methods.  

The child inherits both from all of its ancestors.

11

12

Class VehicleClass Vehicle extends extends ObjectObject // not necessary // not necessary{{ // data// data

// methods ( functions)// methods ( functions) }}

Class Car Class Car extends Vehicleextends Vehicle{{ // data - -

// methods ( functions)// methods ( functions)

//some data and methods can be inherited from Vehicle//some data and methods can be inherited from Vehicle

}}

13

ClassVehicle

Method 1

Method 2

Method 3

Class CarInherits all of the above methods and

can add methods of its own

CODE REUSE

A programmer can tailor a child class by :

adding new variables or methods,

or by modifying the inherited ones

Software reuse Software reuse is the fundamental benefit of inheritancefundamental benefit of inheritance

14

CODE REUSE

We can create new software by reusing existing software components to create new

ones,

we capitalize on all the effort we capitalize on all the effort spent on the design,

15

16

Class Accountdeposit()

Class SavingsAcco

untInherits

deposit ()

Class SeniorAccount

Inherits deposit()

Inheritance

///*************MOST IMPORTANT******

When changes are made on the parent information,

all child classes automatically are changed also.

.

17

CODE REUSE Thus the models that are created are :Thus the models that are created are :

easier to modify and easier to modify and

easier to implementeasier to implement

18

Concepts to Review WHAT IS AN “ISA” Relationship?

What is Encapsulation?

What are the benefits of Inheritance?

What does “Code Reuse” mean in terms of efficiency?

What effect does a code change in the parent class have on a child class?

19

T he reserved word extends sets up an inheritance relationship

To declare a subclass you would write:

class subclass extends SuperClass { . . . } or,

class Dictionary extends Book{…}

A Java class can have only one direct superclass. 

20

Sub or Child Classes

class ParentClass // the super class{ protected int num; // instance variable

public ParentClass(int num) // constructor { this. num = num;}

21

class ParentClass{ protected int num; // instance variable

public ParentClass (int num) // constructor// constructor { this. num = num;

}

*******************************************class ChildClass extends ParentClass {

private float num1; // instance variable

public ChildClass(int newnum, float num1) // Constructor {

super(newnum); // calls parent class constructor this.num1 = num1;

}} 22

Using super

The child class inherits the varible num declared in the parent class ?

How does the child class set up a value for the variable num it inherits?

23

INHERITANCE

TO create an instance of the Childclass we use:

Childclass child = new Childclass ( 20, 30);

How does it set up memory for the variable “num ‘ it inherits?

24

We create a child object :Childclass child = new Childclass ( 20, 30);

In the first line of the child’s constructor,

public ChildClass(int newnum, float num1) // child Constructor { // it calls the parent class constructor with this code super(newnum); // calls parent class constructor

This is the parent class constructor

public ParentClass (int num) // constructor// constructor { this. num = num;

}// So the value in newnum is stored in the parent class num 25

Deriving Subclasses

In Java, we use the reserved word extends to establish an inheritance relationship

class Car extends Vehicle{

// class contents

}

26

Controlling Inheritance Visibility modifiers

determine which class members get inherited

Variables and methods declared with public visibility are inherited, and

those with private visibility are not

27

PROTECTED VISIBILITY MODIFIER But public instance variables violate our goal of

encapsulation

(DO NOT USE THEM IN THIS COURSE!!!)

SO -------

There is a third visibility modifier : protected

28

The protected Modifier

The protected visibility modifier allows a

member of a base class to be inherited into the child class

Encapsulation requires that we protect our protect our instance variables from outside access.

29

30

Accessibility Summary

 Modifier on members in a class

Accessed from the same class

Accessed from the same class clpackage

Accessed from a subclass

Accessed from a different package

public

protected -

default - -

private - - -

Class Book//-------------------------------------------------------------------// Class Book serves as a parent class for class Dictionary//-------------------------------------------------------------------class Book { protected int pages = 1500;//========================================// Prints a message using the value of an instance variable.//======================================== public void page_message () { System.out.println ("Number of pages: " + pages); } // method page_message} // class Book

31

//-------------------------------------------------------------------

class Dictionary extends Book { private int definitions = 52500; //========================================= // Prints an instance variable declared in this class and // an instance variable one that it inherited from Book//======================================

public void definition_message () {

System.out.println ("# of definitions: " + definitions); System.out.println ("Definitions per page: " + definitions/pages); } // method definition_message} // class Dictionary

32

Class Words//=====================================// Instantiates a child class and calls its inherited methods.//===================================== public static void main (String[] args) { // create object of Dictionary class(child of Word Class) Dictionary webster = new Dictionary ();

webster.page_message(); // method defined in Book class webster.definition_message(); //method in Dictionary class } // method main} OUTPUT: “ “ Number of pages: 1500”Number of pages: 1500” “ “ # of definitions: 52500/1500 Definitions per page: "# of definitions: 52500/1500 Definitions per page: " 33

Default Constructor In the previous slide, we created an object of the

Dictionary class.

Dictionary webster = new Dictionary ();

But the Dictionary class has no coded constructor.

How can this be? All classes must have a constructor

34

default constructor

Answer:

The default constructor is called if a class has no coded constructor.

This happens when instance variables already have a value.

So no constructor is needed.

35

The Super Reference

Constructors are Constructors are not inheritednot inherited, ,

even though they have even though they have public public visibilityvisibility !!!! !!!!

So we need to call the So we need to call the parent class constructor parent class constructor

to give values to to give values to the instance variables the instance variables in the parent classin the parent class

To do this, we use The “To do this, we use The “super”super” reference . reference .36

The The supersuper reference reference

The The supersuper reference in a child constructor reference in a child constructor

calls the parent class constructor. calls the parent class constructor.

The call must made in The call must made in first line first line of the constructorof the constructor

e.g super(parameters)

37

//----------------------------------------------------------//  Class Book ‘s constructor initializes pages.// Instance variable “pages”  has no value to start//------------------------------------------------------------class Book 2{ protected int pages; // instance variable

//---------------------------------------------------------------- // Sets up a book with the specified number of pages. //----------------------------------------------------------------public Book 2(int num_pages) { pages = num_pages; // sets number of pages } // constructor Book} // class Book2

38

//=======================================// //prints out the number of pages in a book

//======================================= public void page_message () {

System.out.println ("Number of pages: " + pages);

} // method page_message // Close class Book2

39

//------------------------------------------------------------------------------------------- // Class Dictionary demonstrates the interaction between the constructors of

parent and child classes.// __________________________________________________ class Dictionary2 extends Book 2{ private int definitions; // child class instance variable //-----------------------------------------------------------------------------------------// CONSTRUCTOR USES the super reference to call parent class Book's

constructor.//_________________________________________________________ public Dictionary2 (int num_pages, int num_definitions) {// “super” calls parent class constructor and sends it the number of pages

super (num_pages); definitions = num_definitions; // sets # of definitions } // constructor Dictionary 40

Dictionary2 class//========================================= // Prints an instance variable declared in this class and // an instance variable one that it inherited from Book//======================================   public void definition_message ()   {    System.out.println ("# of definitions: " + definitions);      System.out.println ("Definitions per page: " +      definitions/pages);   }  // method definition_message

NOTE that pages is inherited from the parent class41

//----------------------------------------------------------// Driver class that creates an object of the Dictionary2 class. //------------------------------------------------------------class Words2

{ public static void main (String[] args) { /// Dictionary2 is child of class Book2

Dictionary2 webster = new Dictionary2 (1500, 52500); //webster calls method from the parent Book class webster.page_message(); // webster calls method from Dictionary class webster.definition_message();

} // method main} // class Words2

42

Review I want to create an object of the child class Dictionary2 –

Dictionary2 inherits the number of pages from its parent Book 2

HOW Did I GIVE A VALUE TO the inherited variable Num_Pages?

How do I create an object of Dictionary2?

How many parameters do I use for the constructor ?43

Class Diagram for Words

44

Book2# pages : int

+ pageMessage() : void

Dictionary2- definitions : int

+ definitionMessage() : void

Words2+ main (args : String[]) : void

The Super Reference – Rules - In Words2.java The Dictionary2 class uses the super reference to call

the parent constructor

so that the number of pages can be set.

Java requires that a child class must call the parent class constructor using “super”

IF and ONLY IF the the parent class constructor has parent class constructor has one or more one or more parametersparameters..

45

SUPER and Constructors

This This insuresinsures that the parent class’s that the parent class’s instance variables instance variables are are given given valuesvalues..

If the If the parent class constructor has no parameters, parent class constructor has no parameters,

the the child class is not required to call it. child class is not required to call it.

  A A default constructor default constructor is called for the is called for the parent class parent class instead.instead.

46

Key Terms to Review

Visibility modifiers: protected

The Super Reference

47

Super Reference - A review

When we create the constructor for a child class,

we call the constructor for the super class.

This is done in the first line of the sub class constructor

// it initializes the # of pages in parent class variable pages

super(num_pages)

48

OVERLOADED CONSTRUCTORS:

We might have a constructor for a Rectangle class with one parameter

public Rectangle(int width) {    .. Initialize instance variables} 

49

50

50

Overloaded Constructors Another constructor could be defined by a

Rectangle with two parameters:

public Rectangle(int length, int width) { this.length = length; // shortcut assignment this.width = width }

Both constructors share the same nameshare the same name,,

Rectangle(variables)

but they have different parameter lists.

OVERLOADED CONSTRUCTORS

The compiler determines which constructors to use based on the

 number and types of the parameters to the constructor. 

E.g // calls a constructor with one parameter Rectangle rect = new Rectangle(20); // requires a constructor with two parameters Rectangle rect2 = new Rectangle(20,30);

51

Overloaded constructors

// calls a constructor with one parameter Rectangle rect = new Rectangle(20); // requires a constructor with two parameters Rectangle rect2 = new Rectangle(20,30);

Each Rectangle object, rect and rect2, call a different constructor

52

5353

Overloading Methods – similar to overloaded Overloading Methods – similar to overloaded constructorsconstructors

Method Method overloadingoverloading is the process of is the process of using the using the same method name same method name for for multiple methods. multiple methods.

The signature of each overloaded method must be unique

The signature is based on the number, type, and order of the parameters.

Method Overloading The compiler determines the version of the

method being invoked by :

analyzing the parameters.

The return type of the method is not part of the signature!

54

5555

Overloading Methods

5656

Overloaded Methods The println method is overloaded: println (String s) println (int i)

println (double d) etc.

The following lines invoke different versions of the println method:

System.out.println ("The total is:");

System.out.println (total);

Overriding Methods

A child class can override the definition of an inherited method in favor of its own.

This is different from the overloading that we used in constructors.

A child class can can redefineredefine a method a method it inherits from its parent.

57

Overriding Methods

The new method must have the same signature as the parent's method,

but can have different code in the body

Same signature = same number and type of parameters etc.

58

//**********************************************// Contains a method that is overridden in a child class.//**********************************************

class Thought { public void message() { System.out.println ("I feel like I'm diagonally parked " +

"in a parallel universe."); } // method message} // class Thought

59

//------------------------------------------------------------------------// Class Advice overrides the message method.// it keeps same method name and number of parameters//____________________________________________class Advice extends Thought {// This method overrides the parent version, public void message() { System.out.println ("Warning: Dates in calendar are " +

"closer than they appear."); } // method message} // class Advice

60

///**********************************************// Driver class that creates objects of parent and child classes. // __________________________________________________class Messages {public static void main (String[] args) { Thought parked = new Thought(); // create Thought object

Advice dates = new Advice();// create Advice object

parked.message(); // calls method in Thought class

dates.message(); // calls method in Advice class

} // method main} // class Messages

61

Overloading vs. Overriding

Don't confuse the concepts of

overloading and overriding

Overloading : deals with multiple methods in the same class

With the same name but with different signatures

62

Overriding vs Overloading

Overriding deals with two methods,

one in a parent class and

one in a child class,

That both have the same signature

63

Overloading VS Overriding

Overloading lets you define a method in different ways

for different data in the same class

Overriding lets you define a method in a child class

that has the same signature as the parent class

But

Implements it differently Implements it differently from the parent classfrom the parent class64

MOST IMPORTANT!!!!

To overload a method in the same class

You must duplicate the method name,

but use a different argument list.

65

OverRiding a method

To override a method,

you must match the entire method signature -

same argument list

AND The method overridden is in the parent class

66

Class Hierarchies

Two children of the same parent are called siblings.

Good class design puts all common features as high in the hierarchy as is possible.

67

Single vs. Multiple Inheritance

Java supports single inheritance, meaning that a derived class can have only one parent class

Multiple inheritance allows a class to be derived from two or more classes,

inheriting the members of all parents’ classes This causes “Collisions”, such as the same variable name in two

parents, have to be resolved

68

The Object Class

The class Object is defined in the java.lang package of the Java standard class library

All classes are derived from the Object class

The ObjectObject class class is therefore the

ultimate root of all class hierarchiesultimate root of all class hierarchies

69

The Object Class The Object class contains a few useful methods, inherited by all classes, e.g.

The toString method in the object class : 1. prints out the name of the class and 2. its memory address (hexadecimal representation of

the hash code of the object)

We override the We override the toStringtoString method method in OUR classes to in OUR classes to output the instance variables in output the instance variables in OUR classOUR class

70

71

Class ObjectClass Object The class Object defines the following methods:

• clone() --we use• equals(Object obj) -- we use• finalize()• getClass() - we use• hashCode() - we use sometimes• notify()• notifyAll()• toString() -- we use• wait()• wait(long timeout)• wait(long timeout, int nanos)

As you can see, this list includes three overloaded versions of the method named wait

Class Object Because every class is

either a direct or indirect subclass of Objectdirect or indirect subclass of Object,

every class in Java inherits these eleven methods. inherits these eleven methods.

Many of these eleven methods are intended to be overridden for various purposes.

However, some of them, such as getClass, notify, and wait, getClass, notify, and wait, are intended to be used directly without overriding. to be used directly without overriding.

72

The super Reference Revisited

A method in the parent class can be invoked explicitly using super.methodName(parameters)

To call a method in the parent class, the syntax is:

super.method(parameters)

73

public class Student{ protected String Firstname, Lastname; protected int numCourses; //----------------------------------------------------------------- // Sets up a student with a name and number of courses. //----------------------------------------------------------------- public Student (String Firstname, String Lastname, int

numCourses) { this.Firstname = Firstname;

this. Lastname = LastName this.numCourses = numCourses; } (con’d)

74

To String method//----------------------------------------------------------------- // Returns information about this student as a string. // Used in System.out.println calls – typical toString //----------------------------------------------------------------- public String toString () { String result = "Student name: " + Firstname + “ “ +

Lastname "\n";

result += "Number of courses: " + numCourses;

return result; }(con’d) 75

//method to compare two objects// Uses String class equals method to do comparison// String class overrides equals method of Object class

public boolean equals(Object other){ boolean result = false;

if (LastName.equals(((Student)other).LastName)) result = FirstName.equals(((Student)other).FirstName); return result; }}

76

public class GradStudent extends Student{ private String source; // instance variables private double rate; //----------------------------------------------------------// Sets up the gradate student using the specified information. Parameters

include values for parent class instance variables//------------------------------------------------------------- public GradStudent (String Fastname, String LastName , int

numCourses, String source, double rate) { // call parent class constructor to initialize its instance variables super (Firstname, Lastname, numCourses);

// initalize this class’s instance variables this.source = source; this.rate = rate; }

77

ToString method//-----------------------------------------------------------------// Returns a description of this graduate student as a string. –

uses super to call parent class toString() and adds some data declared in this class

//----------------------------------------------------------------- public String toString ()

{ // call parent class toString method and store in “result”call parent class toString method and store in “result”

String result = super.toString();

// add instance variables of this class to “result”

result += result += "\nSupport source: " + source + "\n” + "Hourly pay rate: " + rate;

return result; }} 78

class Academia{ //---------------------------------------------------- // Creates objects of two student types, prints some //information

about them, then checks them for equality. //----------------------------------------------------- public static void main (String[] args) { Student susan = new Student ("Susan", “James”, 4);

GradStudent Paul = new GradStudent ("Paul",”McCartney” , 1,“Gov’t”, 10.00);

System.out.println (susan); // uses toString method in Student System.out.println (Paul); // uses toString method in GradStudent // calls equals method in Student which compares last and first names

- if (!susan.equals(Paul)) System.out.println ("These are two different students."); }}

79

OUTPUT FOR Susan & Paul

From the toString method in Student class for object Susan toString() { "Student name: " + Firstname + “ “ + Lastname "\n"; result += "Number of courses: " + numCourses;

Output FOR SUSAN: Susan James Number of courses 4

From the toString method in gradStudent for object PaultoString (){ String result = super.toString(); // invokes parent class toString)( see above)// invokes parent class toString)( see above)

// concatenate instance variables of this class to “result” result += result += "\nSupport source: " + source + "\n” + "Hourly pay rate: " + rate; return result;}

Output for GradStudent PAULPaul McCartney Number of courses 1Support source Gov’t Hourly pay Rate 10.00

80

Grad Student uses parent to String() So the grad student class makes use of the toString

method in the parent class

AND adds new values particular to

the GradStudent class.

81

REVIEW What is overloading - for Constructors AND class methods

What is overriding

How do they differ

What does equals method in Object class do. What does equals method DO in child classes

What does toString method in Object class return What does toString method implemented in your class

return 82

Recommended