inheritance chapter 7. outline inheritance basics programming with inheritance dynamic binding and...

70
Inheritance Chapter 7

Upload: suzanna-jones

Post on 17-Jan-2018

230 views

Category:

Documents


0 download

DESCRIPTION

Inheritance Basics: Outline Introduction to Inheritance Derived Classes Overriding Method Definitions Overriding vs. Overloading The final Modifier

TRANSCRIPT

Page 1: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Inheritance

Chapter 7

Page 2: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Outline

• Inheritance Basics• Programming with Inheritance• Dynamic Binding and Polymorphism

Page 3: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Inheritance Basics: Outline

• Introduction to Inheritance• Derived Classes• Overriding Method Definitions• Overriding vs. Overloading• The final Modifier

Page 4: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Introduction to Inheritance

• Inheritance allows us to define a general class and then more specialized classes simply by adding new details to the more general class definition.

• A more specialized class inherits the properties of the more general class, so that only new features need to be programmed.

Page 5: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Introduction to Inheritance, cont.

• example– General class Vehicle might have instance

variables for weight and maximum occupancy.

– More specialized class Automobile might add instance variables for wheels, engine size, and license plate number.

– General class Vehicle might also be used define more specialized classes Boat and Airplane.

Page 6: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Programming Example: A Base Class

Page 7: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Derived Classes• Consider a college record-keeping system with

records about students, faculty and (nonteaching) staff.

Page 8: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Derived Classes, cont.

• Even though your program may not need any Person or Employee objects, these classes can be useful for consolidating and representing features common to all subclasses.– For example, all students, faculty, and staff

have names, and these names may need to be initialized, changed, retrieved, or printed.

Page 9: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Derived Classes, cont.• class Student is a derived class of class Person

and class Person is called the base class.

Page 10: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Derived Classes, cont.

• syntaxpublic class Derived_Class_Name extends

Base_Class_Name{

Declarations_of_Added_Instance_Variables

Definitions_of_Added_and_Overridden_Methods

}

Page 11: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Derived Classes, cont.

• When you define a derived class, you declare only the added instance variables and you define only the added and overridden methods.

• The variables and methods of the parent class which are not declared private are inherited automatically.

Page 12: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Derived Classes, cont.

Page 13: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Overriding Method Definitions

• Notice that class Student has a method writeOutput with no parameters, and class Person also has a method writeOutput with no parameters, that class Student inherits.

• When a derived class defines a method with the same name and the same number and types of parameters as a method in the base class, the method in the derived class overrides the method in the base class.

Page 14: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Overriding Method Definitions, cont.

• When overriding a method, you can change the method definition to anything you wish, but you cannot change the method’s heading or the method’s return type.

Page 15: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Overriding vs. Overloading

• When you override a method, the new method definition in the derived class has the same name and the same number of types of parameters as the method definition in the base class.

• When the name is the same, but the number or types of the parameters differs, whether in the base class or in the derived class, the method is overloaded in the derived class.

Page 16: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Overriding vs. Overloading, cont.

• example: public String getName(String title)

in class Student and public String getName()

in class Person overload method getName since the two methods have different parameter lists.

– Both methods are available in class Student.

Page 17: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

The final Modifier

• You can prevent a method definition from being overridden by adding the word final to the method heading.

• examplepublic final void someMethod(){…

• This is used rarely, but it produces more efficient code.

Page 18: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

The final Modifier, cont.

• An entire class can be declared final, in which case it cannot be used as a base class to derive another class.

Page 19: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Private Instance Variables in the Base Class

• Private instance variables inherited from a base class cannot be accessed directly.

• Instead, they must be accessed using a method that is not declared private.

• While this may seem inconvenient, it provides an important mechanism for controlling access and changes to instance variables in the base class.

Page 20: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Private Methods in the Base Class

• Like private instance variables, private method inherited from a base class cannot be accessed directly.

• Instead, they, too, must be accessed using a method that is not declared private.

• This, too, provides an important mechanism for controlling access to methods in the base class.

• Since private methods typically serve as helping methods, their use always is limited to the class in which they are defined.

Page 21: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Programming with Inheritance: Outline

• Constructors in Derived Classes• (optional) The this Method• Calling an Overridden Method• (optional) A Subtle Point About Overloding

and Overriding• The class Object• Abstract Classes• Interfaces

Page 22: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Constructors in Derived Classes

• A base class has its own constructors.– Their purpose typically is to initialize the

instance variables declared in the base class.

• A derived class has its own constructors.– Their purpose typically is to call a

constructor in the base class, and then to initialize the instance variables declared in the derived class.

Page 23: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Constructors in Derived Classes, cont.

• To call a constructor in the base class, usesuper(Values_for_Instance_Variables

_Declared_in_the_Base_Class);

• examplesuper(initialName);

notPerson(initialName); //ILLEGAL

Page 24: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Using super

• The call to the constructor in the base class (using super) must be the first action taken in the constructor of a derived class.

• When no call to the constructor in the base class is included, Java automatically includes a call to the default constructor in the base class.

Page 25: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Using super, cont.• equivalent definitions:

public Student(){super();studentNumber= 0;

}

andpublic Student(){studentNumber= 0;

}

Page 26: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

(optional) The this Method

• Within the definition of one constructor, it can be appropriate to call another constructor in the same class.

• The keyword this is used to call another constructor in the same class.

• examplethis(initialName, 0)

Page 27: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

(optional) The this Method, cont.

• Any use of this must be the first action in the constructor definition.– Thus, a constructor definition cannot

contain a call using super and a call using this.

• To use both super and this, include a call using this in one constructor and a call using super in the constructor called using this.

Page 28: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Calling an Overridden Method

• super can be used to call a method in the base class that has been overridden in the derived class.

• examplesuper.writeOutput();

• However, you cannot repeat the use of super to invoke a method in some ancestor class other than the immediate base (parent) class.

Page 29: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Programming Example: Multilevel Derived Classes

• Class Undergraduate can be derived from class Student which is derived from class Person.

• Class Undergraduate will have all the instance variables and methods of class Student which has all the instance variables and methods of class Person.

Page 30: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Programming Example: Multilevel Derived Classes, cont.

Page 31: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Programming Example: Multilevel Derived Classes,

cont.

Page 32: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Terminology

• A base class often is called a parent class.• A derived class then is called a child class.• A class that is a parent of a parent of…a

parent of (with one or more “parent of”s) another class often is called an ancestor class.

• A class than is a child of a child of…a child of (with one or more “child of”s) often is called a descendant.

Page 33: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

(optional) A Subtle Point About Overloading and

Overriding• Even when two methods have the same

number of parameters, a difference in parameter type is sufficient to qualify for overloading.

• But, a reference to an ancestor class type can refer to a descendant type.

• Hence an overridden method in an ancestor class sometimes needs to be invoked explicitly using super.

Page 34: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

An Object Can Have More than One Type

• If class Undergraduate is derived from class Student and class Student is derived from class Person, then every object of class Undergraduate is also an object of class Student and an object of class Person.

• A reference to an object of class Undergraduate can be substituted for a reference to an object of class Student or a reference to an object of class Person.

Page 35: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

An Object Can Have More than One Type, cont.

• Givenpublic static void compareNumbers (Student s1, Student s2)

then eitherSomeClass.compareNumbers(studentObject, undergradObject);

orSomeClass.compareNumbers(undergradObject, studentObject);

could be used.

Page 36: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

An Object Can Have More than One Type, cont.

• However, a reference to an object of class person cannot be substituted for a reference to an object of class Student or an object of class Undergraduate.

• A reference to an object of an ancestor cannot be substituted for a reference to an object of a derived class.

Page 37: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

An Object Can Have More than One Type, cont.

• Hence, givenpublic static void compareNumbers (Student s1,

Student s2)

neitherSomeClass.compareNumbers

(studentObject, personObject);

norSomeClass.compareNumbers(personObject, studentObject);

could be used.

Page 38: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

“Is a” and “Has a” Relationships

• A derived class is a more specialized class than its base class or any of its ancestor classes.– For example, a student is a person.

• A more complex object has as one or more of its instance variables one or more references to objects of a simple class, exhibiting a has a relationship.– For example, a person has a name.

Page 39: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

The Class Object

• In Java, every class descends from (and inherits features from) the Object class.

• Therefore, every object of every class is of type Object.

• Unless a class is declared explicitly to be a descendant of some other class, it is an immediate descendant of the class Object.

Page 40: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

The Class Object, cont.

• An object of any class can substituted when a parameter of type Object is expected.

• Every class inherits some methods from the class Object:– equals()– toString()

but usually these methods are overridden by the derived class or by an intermediate ancestor class.

Page 41: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Method toString

• Inherited method toString takes no arguments.

• Typically, method toString is coded to produce and return a string which contains everything of interest about the object.

Page 42: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Method toString, cont.

• examplepublic String toString();{return (“Name: “ + getName()+ \n + “Number: “ + getNumber());

}

• Whenever a new class is created, a suitable toString method should be defined.

Page 43: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Method toString, cont.

• Method toString can be called my the conventional means, Object_Name.toString, or by using only Object_Name.

• exampleSystem.out.println(s.toString());

orSystem.out.println(s);

Page 44: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Method clone

• Method clone also is inherited from the class Object.

• Method clone takes no arguments and returns a copy of the calling object.– Even though the data is identical, the

objects are distinct.• Typically, method clone needs to be

overridden to function properly.– See Appendix 8 for more details.

Page 45: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Abstract Classes

• An abstract class is not intended to be used to create objects.

• Class Figure is an example of a class used as a base class to derive other classes including class Box and class Triangle.– Nevertheless, as written, objects of class Figure could be instantiated and its methods used, even though that was not our intention.

Page 46: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Abstract Classes, cont.

• By declaring one or more methods to be abstract and by omitting the method body, only objects of derived classes which override the method(s) can be instantiated.

• examplepublic abstract void drawHere();

• A class that has at least one abstract method must be declared abstract.

Page 47: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Abstract Classes, cont.• example

public abstract class Figure{…

Page 48: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Abstract Classes, cont.

• An abstract class serves as a placeholder.• An abstract class makes it simpler to define

derived classes.• An abstract class assures that all its derived

classes implement its abstract method(s), or they too will be abstract.

Page 49: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Interfaces

• An interface specifies the headings for methods that must be defined for any class that implements the interface.

Page 50: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Interfaces, cont.

• To implement an interface, a class must– include the phraseimplements Interface_Name

at the start of the class definition • example

implements MyInterface, YourInterface

– implement all the method headings listed in the definition of the interface.

Page 51: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Interfaces, cont.

Page 52: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Interfaces, cont.

• An interface is a type.• A method may have a parameter of an

interface type.• Any class that implements the interface can

be substitute for the parameter.• A class can implement any number of

interfaces by providing implementations for all the methods of all the interfaces it claims to implement.

Page 53: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Dynamic Binding and Polymorphism: Outline

• Dynamic Binding• Type Checking and Dynamic Binding• Dynamic Binding with toString• Polymorphism

Page 54: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Dynamic Binding

• Different objects can invoke different method definitions using the same method name.

• For example, if b references a Box and t references a Triangle, b and t invoke different definitions of method drawAt even of b and t are declared to be objects of type Figure.

Page 55: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Dynamic Binding, cont.

• Handling the invocation of a method that may be overridden later is called dynamic binding or late binding.

• The type of object being referenced at the time of the method call, not the type of reference that was declared, determines which method is invoked.

Page 56: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Dynamic Binding, cont.

• ConsiderFigure f;Box b = new Box(1, 4, 4);f = b;f.drawAt(2);Triangle t = new Triangle(1,2);f = t;f.drawAt(2);

Page 57: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Dynamic Binding, cont.

• Method drawAt is inherited from class Figure and is not overridden.

• But, method drawHere is invoked within the definition of method drawAt, and method drawHere is overridden.

• The type of object referred to by f determines which method drawHere is invoked.

Page 58: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Type Checking and Dynamic Binding

• Recall that an object reference to an ancestor class can refer to an object of a descendant class.Employee e = new Employee();Person p;p = e;

• However, you can invoke only a method in class Person with the variable p.

Page 59: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Type Checking and Dynamic Binding, cont.

• However, if a method is overridden in the class Employee, and variable p references an Employee object, then the method in class Employee is used.

• The variable determines what methods can be used, but the type referenced by the object determines which definition of the method will be used.

Page 60: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Type Checking and Dynamic Binding, cont.

• To use a method name in the class Employee with an object named by the variable p of type Person, use a type cast.

• exampleEmployee e = (Employee)p;e.setEmployeeNumber(5678);

Page 61: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Type Checking and Dynamic Binding, cont.

• However, even a type cast cannot fool Java–exampleBox b = new Box (1, 4, 4);Figure f = (Figure)b;

f. drawHere()

will use the definition of drawHere given in class Box, not the definition of drawHere given in class Figure.

Page 62: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Type Checking and Dynamic Binding, cont.

• You are unlikely to assign an object of a descendant type to a variable of a parent type, at least not directly.

• But, such an assignment can occur indirectly by providing an argument of a descendant type for a method that has a parameter of an ancestor type.

Page 63: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Dynamic Binding with toString

• Recall method toString typically is used to prepare and return a string, describing an object, for output to the screen.

• The name of this method can be omitted, thanks to dynamic binding, because one definition of method println expects a single argument of type Object which it uses to invoke the method toString associated with the object.

Page 64: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Polymorphism

• Polymorphism comes from Greek meaning “many forms.”

• In Java, polymorphism refers to the dynamic binding mechanism that determines which method definition will be used when a method name has been overridden.

• Thus, polymorphism refers to dynamic binding.

Page 65: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Subtle Difference

• Dynamic binding refers to the process carried out by the computer.

• Polymorphism can be thought of as something objects do.

• Polymorphism, encapsulation, and inheritance, are considered to be the main features of object-oriented programming.

Page 66: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

(optional) A Better equals Method

• Sometimes method equals from class Object is overloaded when it should have been overridden.– This occurs when its parameter is not of

type Object.• Usually, this is all right.

Page 67: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

(optional) A Better equals Method, cont.

• But, if method equals is called with an object of class Object as its argument, method equals from class Object will be invoked.

• The problem is fixed by changing the formal parameter in the overriding method so that it is a parameter of type Object.

Page 68: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

(optional) A Better equals Method, cont.

• However, this allows the argument to be any type of object, which can produce a run-time error.

• But, we can determine if an object is of the correct type usingObject instanceof Class_Name

• Finally, we should return false when comparing an object to a null reference.

Page 69: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

(optional) A Better equals Method, cont.

Page 70: Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism

Summary

• You have become acquainted with inheritance.

• You have learned how to define and use derived classes.

• You have learned about dynamic binding and polymorphism.