73
1 Inheritance Inheritance Another fundamental object-oriented Another fundamental object-oriented technique is called inheritance, which technique is called inheritance, which enhances software design and promotes enhances software design and promotes reuse reuse We will focus on: We will focus on: deriving new classes deriving new classes creating class hierarchies creating class hierarchies the the protected protected modifier modifier polymorphism via inheritance polymorphism via inheritance inheritance used in graphical user inheritance used in graphical user interfaces interfaces

1Inheritance Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse We will focus on:

Embed Size (px)

Citation preview

Page 1: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

1

InheritanceInheritance

Another fundamental object-oriented technique is called Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes inheritance, which enhances software design and promotes reusereuse

We will focus on:We will focus on:

• deriving new classesderiving new classes

• creating class hierarchies creating class hierarchies

• the the protectedprotected modifier modifier

• polymorphism via inheritancepolymorphism via inheritance

• inheritance used in graphical user interfacesinheritance used in graphical user interfaces

Page 2: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

2

The Three Pillars of OOPThe Three Pillars of OOP

The Three Pillars of OOPThe Three Pillars of OOP

EncapsulationEncapsulation InheritanceInheritance PolymorphismPolymorphism

   Every class in Java extends some other class. If you don't Every class in Java extends some other class. If you don't

explicitly specify the class that your new class extends, it will explicitly specify the class that your new class extends, it will automatically extend the class named Object. automatically extend the class named Object.

Page 3: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

3

Class HierarchyClass Hierarchy

Java uses a class hierarchy to organize its classes.Java uses a class hierarchy to organize its classes.

   Thus, all classes in Java exist in a class hierarchy where the Thus, all classes in Java exist in a class hierarchy where the

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

   Some classes extend Object directly, while other classes are Some classes extend Object directly, while other classes are

subclasses of Object further down the hierarchy. subclasses of Object further down the hierarchy.

Page 4: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

4

InheritanceInheritance

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

The existing class is called the The existing class is called the parent class,parent class, or or superclasssuperclass, or , or base classbase class

The derived class is called the The derived class is called the child classchild class or or subclasssubclass..

Page 5: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

5

InheritanceInheritance

As the name implies, the child inherits characteristics of As the name implies, the child inherits characteristics of the parent. the parent.

That is, the child class inherits the methods and data That is, the child class inherits the methods and data defined for the parent classdefined for the parent class

This means that you can write the code for one class This means that you can write the code for one class and have all its child classes have access to it.and have all its child classes have access to it.

Page 6: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

6

InheritanceInheritance

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

Vehicle

Car

Proper inheritance creates an Proper inheritance creates an is-ais-a relationship, meaning relationship, meaning the child the child is ais a more specific version of the parent more specific version of the parent

Page 7: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

7

InheritanceInheritance

A subclass A subclass inheritsinherits state state and and behavior. behavior.

Recall that an object’s state is reflectedRecall that an object’s state is reflected in the in the form of instance form of instance variables and its behavior in the form of methodsvariables and its behavior in the form of methods. .

The child inherits both from all of its The child inherits both from all of its ancestors.ancestors.

Page 8: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

8

InheritanceInheritance

Child classes can use the items inherited from its Child classes can use the items inherited from its parent parent or or super super class class as isas is, or the child class can modify or override , or the child class can modify or override the methods of the parent class.the methods of the parent class.

This means that the child class can contain a method with This means that the child class can contain a method with the same name as the parent class.the same name as the parent class.

Page 9: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

9

InheritanceInheritance

A programmer can tailor a derived class as needed by A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the adding new variables or methods, or by modifying the inherited onesinherited ones

Software reuseSoftware reuse is a fundamental benefit of inheritance is a fundamental benefit of inheritance

By using existing software components to create new ones, By using existing software components to create new ones, we capitalize on all the effort that went into the design, we capitalize on all the effort that went into the design, implementation, and testing of the existing softwareimplementation, and testing of the existing software

Page 10: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

10

Child ClassesChild Classes

The method in the child class deals with the behavior The method in the child class deals with the behavior that is particular to the child class. that is particular to the child class.

We have a class We have a class SHAPESHAPE and and SHAPESHAPE has a child class has a child class RECTANGLERECTANGLE and a child class and a child class TRIANGLTRIANGLE. E.

The SHAPE class will contain methods that are The SHAPE class will contain methods that are common to both child classes, e.g. and Area() methodcommon to both child classes, e.g. and Area() method

Both child classes will have a method that calculates its Both child classes will have a method that calculates its Area. Area.

Only the formulas for each Area calculation will differ.Only the formulas for each Area calculation will differ.

Page 11: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

11

InheritanceInheritance

This leads to smaller and easier to understand systems.This leads to smaller and easier to understand systems.

Using inheritance, common descriptions can be reused, Using inheritance, common descriptions can be reused, promoting the concept of code reusability. promoting the concept of code reusability.

A child class can have a method with the same name as A child class can have a method with the same name as the parent class only its method implements what it is the parent class only its method implements what it is capable of doing.capable of doing.

Page 12: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

12

InheritanceInheritance

Inheritance cuts redundancy as descendant classes only Inheritance cuts redundancy as descendant classes only implement the extra information that differentiates them implement the extra information that differentiates them from the parent classfrom the parent class

When changes are made on the common information, all When changes are made on the common information, all child classes automatically inherit it.child classes automatically inherit it.

Thus the models that are created are easier to modify and Thus the models that are created are easier to modify and implement.implement.

In Java, the reserved wordIn Java, the reserved word extendsextends is used to establish an is used to establish an inheritance relationshipinheritance relationship

Page 13: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

13

Sub Sub or or Child Child ClassesClasses

To declare a subclass you would write:To declare a subclass you would write:

class subclass extends SuperClass { . . . } or,class subclass extends SuperClass { . . . } or,

class Dictionary extends Book{…}class Dictionary extends Book{…}

A Java class can have only one direct A Java class can have only one direct superclass.superclass.

Member variables defined in the subclass hide member Member variables defined in the subclass hide member variables of the same name in the superclass. Consider variables of the same name in the superclass. Consider this superclass and subclass pair:this superclass and subclass pair:

Page 14: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

14

Sub Sub or or Child Child ClassesClasses

class Super {class Super {

protected int protected int num;num;

public Super(int anum){public Super(int anum){ num = anum;num = anum;

}}

class Sub extends Super {class Sub extends Super { float float num1;num1;

public Sub(int newnum, float Fnum) {public Sub(int newnum, float Fnum) { super(newnum)super(newnum) num1 = Fnum;num1 = Fnum;

}}

Page 15: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

15

Deriving SubclassesDeriving Subclasses

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

class Car extends Vehicleclass Car extends Vehicle

{{

// class contents// class contents

}}

See See Words.java Words.java See See Book.java Book.java See Dictionary.java See Dictionary.java

Page 16: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

16

Controlling InheritanceControlling Inheritance

Visibility modifiers determine which class members get Visibility modifiers determine which class members get inherited and which do notinherited and which do not

Variables and methods declared with Variables and methods declared with publicpublic visibility are visibility are inherited, and those with inherited, and those with privateprivate visibility are not visibility are not

But But publicpublic variables violate our goal of encapsulation variables violate our goal of encapsulation

There is a third visibility modifier that helps in inheritance There is a third visibility modifier that helps in inheritance situations: situations: protectedprotected

Page 17: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

17

The The protectedprotected Modifier Modifier

The The protectedprotected visibility modifier allows a member of a visibility modifier allows a member of a base class to be inherited into the childbase class to be inherited into the child

The The protectedprotected visibility modifier provides more visibility modifier provides more encapsulation than encapsulation than publicpublic does. does.

Encapsulation requires that we protect as much as possible Encapsulation requires that we protect as much as possible out instance variables from outside accesss.out instance variables from outside accesss.

The details of each modifier are given in Appendix FThe details of each modifier are given in Appendix F

Page 18: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

18

The The protectedprotected ModifierModifier

The visibility modifiers determine which class members The visibility modifiers determine which class members get inherited and which do not.get inherited and which do not.

Variables and methods declared with Variables and methods declared with publicpublic visibility visibility are inherited, and those with are inherited, and those with privateprivate visibility are visibility are not.not.

But But publicpublic variables violate our goal of encapsulation. variables violate our goal of encapsulation.

The The protectedprotected visibility modifier allows a member to visibility modifier allows a member to be inherited, but provides more protection than be inherited, but provides more protection than publicpublic does. does.

Page 19: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

19

The The supersuper Reference Reference

Constructors are not inherited, even though they have Constructors are not inherited, even though they have public visibilitypublic visibility

Yet we often want to use the parent's constructor to set up Yet we often want to use the parent's constructor to set up the "parent's part" of the objectthe "parent's part" of the object

The The supersuper reference can be used to refer to the parent reference can be used to refer to the parent class, and is often used to invoke the parent's constructorclass, and is often used to invoke the parent's constructor

See Words2.java (page 328)See Words2.java (page 328) See Book2.java (page 329)See Book2.java (page 329) See Dictionary2.java (page 330)See Dictionary2.java (page 330)

Page 20: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

20

Class Diagram for WordsClass Diagram for Words

Book

# pages : int

+ pageMessage() : void

Dictionary

- definitions : int

+ definitionMessage() : void

Words

+ main (args : String[]) : void

Page 21: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

21

The Super ReferenceThe Super Reference

The The supersuper reference can be used to refer to the parent reference can be used to refer to the parent class, and is often used to invoke the parent's constructor.class, and is often used to invoke the parent's constructor.

In Words2.java, The Dictionary class uses the super In Words2.java, The Dictionary class uses the super reference to call the parent constructor so that the number reference to call the parent constructor so that the number of pages can be set. of pages can be set.

If it did not call the parent constructor, it would have to If it did not call the parent constructor, it would have to initialize the number of pages in its own constructor. Let us initialize the number of pages in its own constructor. Let us look at Words2.javalook at Words2.java

Page 22: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

22

Super ReferenceSuper Reference

When we create the When we create the constructor constructor for a child class, we for a child class, we should invoke the constructor for the superclass also. should invoke the constructor for the superclass also.

To do this, the To do this, the first linefirst line of our constructor should contain of our constructor should contain the keyword super followed by a parameter list as though the keyword super followed by a parameter list as though calling a method named super(). calling a method named super().

The parameter list must match the parameters in the The parameter list must match the parameters in the argument list of the superclass constructor.e.g. argument list of the superclass constructor.e.g.

super(num_pages)super(num_pages) // // initializes the # of pages initializes the # of pages

Page 23: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

23

Super ReferenceSuper Reference

This causes the constructor for the superclass to be invoked This causes the constructor for the superclass to be invoked using parameters passed from the subclass. using parameters passed from the subclass.

Thus memory is allocated for all the data in the super class. Thus memory is allocated for all the data in the super class. The child class now has full access to it.The child class now has full access to it.

Page 24: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

24

InheritanceInheritance

The Dictionary class invokes the parent class constructor The Dictionary class invokes the parent class constructor with: with:

super(num_pages)super(num_pages)

Since the Since the Dictionary Dictionary classclass inherits the variable inherits the variable pagespages from from the the parent class parent class BookBook,, it has to initialize this variable in its it has to initialize this variable in its constructor. constructor.

But the parent class constructor already does this But the parent class constructor already does this initialization. initialization.

Since constructors are not inherited, the Dictionary sub Since constructors are not inherited, the Dictionary sub

class can use the class can use the supersuper reference to invoke the parentreference to invoke the parent class class constructor.constructor.

Page 25: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

25

The Super ReferenceThe Super Reference

A child object inherits the allowable fields and methods of A child object inherits the allowable fields and methods of its parent . The one duty of the default constructor is to its parent . The one duty of the default constructor is to support this.support this.

Each instance of a child class inherits the specified Each instance of a child class inherits the specified methods and variables of the parent class. So the parent methods and variables of the parent class. So the parent class’s instance variables must be properly initialized.class’s instance variables must be properly initialized.

Page 26: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

26

Inheritance and ConstructorsInheritance and Constructors

Every constructor has 3 tasks to perform:Every constructor has 3 tasks to perform:

1. 1. Instantiate the parent object and initialize its Instantiate the parent object and initialize its

fieldsfields

2. Initialize any fields local to its class2. Initialize any fields local to its class

3. perform the statements in the constructor3. perform the statements in the constructor

If you do not call the parent constructor with super If you do not call the parent constructor with super when the super class constructor has parameters, then when the super class constructor has parameters, then the instance variables in the parent class will not be the instance variables in the parent class will not be initialized. initialized.

Page 27: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

27

Defined vs. InheritedDefined vs. Inherited

A subtle feature of inheritance is the fact that even if a A subtle feature of inheritance is the fact that even if a method or variable is not inherited by a child, it is still method or variable is not inherited by a child, it is still defineddefined for that child for that child..

An inherited member can be referenced directly in the child An inherited member can be referenced directly in the child class, as if it were declared in the child classclass, as if it were declared in the child class

But even members that are not inherited exist for the child, But even members that are not inherited exist for the child, and can be referenced indirectly through parent methodsand can be referenced indirectly through parent methods

In Eating.Java, a pizza object is created that can access In Eating.Java, a pizza object is created that can access private methods and variables in the parent class.private methods and variables in the parent class.

Page 28: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

28

Overriding MethodsOverriding Methods

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

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

That is, a child can That is, a child can redefine a methodredefine a method it inherits from its it inherits from its parent. parent.

The new method must have the The new method must have the same signaturesame signature as the as the parent's method, but can have different code in the bodyparent's method, but can have different code in the body

Page 29: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

29

Overriding MethodsOverriding Methods

See Messages.java See Messages.java See Thought.javaSee Thought.java See Advice.java See Advice.java

Note that a parent method can be explicitly invoked using Note that a parent method can be explicitly invoked using the the supersuper reference reference

Page 30: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

30

Overloading vs. OverridingOverloading vs. Overriding

Don't confuse the concepts of overloading and overridingDon't confuse the concepts of overloading and overriding

Overloading deals with multiple methods in the same class Overloading deals with multiple methods in the same class with the same name but different signatureswith the same name but different signatures

Overriding deals with two methods, one in a parent class Overriding deals with two methods, one in a parent class and one in a child class, that have the same signatureand one in a child class, that have the same signature

Overloading lets you define a similar operation in different Overloading lets you define a similar operation in different ways for different dataways for different data

Overriding lets you define a similar operation in different Overriding lets you define a similar operation in different ways for different object typesways for different object types

Page 31: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

31

Overriding MethodsOverriding Methods

A subclass can either completely override an inherited A subclass can either completely override an inherited method, or the subclass can enhance it. method, or the subclass can enhance it.

The subclass can use the keyword super to invoke the The subclass can use the keyword super to invoke the version in the superclass. version in the superclass.

For instance, if have a method called For instance, if have a method called deposit()deposit() in the child in the child class and a method called class and a method called deposit()deposit() in the parent class, the in the parent class, the

childchild class would call the parent method with: class would call the parent method with:

super.deposit(45.00)super.deposit(45.00)

Page 32: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

32

OverRidingOverRiding

The object type determines which method is invoked. The object type determines which method is invoked.

Savings_Account s = new Savings_Account(“Tom”); Savings_Account s = new Savings_Account(“Tom”);

Account b = new Account(“Bob”);Account b = new Account(“Bob”);

s.deposit(25.00);s.deposit(25.00); // // defined in Savings_Accountdefined in Savings_Account b.deposit(25.00);b.deposit(25.00); // method defined in Account class// method defined in Account class

Don't confuse the concepts of overloading and overridingDon't confuse the concepts of overloading and overriding

Page 33: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

33

Overriding MethodsOverriding Methods

To To overload overload a method, you must a method, you must duplicate the method duplicate the method namename, but use a , but use a different argument listdifferent argument list. .

To To overrideoverride a method, you must a method, you must match the entire method match the entire method signature. signature.

If you aren't careful when writing your new method If you aren't careful when writing your new method signature, you will be overloading methods when you think signature, you will be overloading methods when you think that you are overriding them. that you are overriding them.

This is a situation where you don't get any warnings from This is a situation where you don't get any warnings from the JDK compiler. the JDK compiler.

Page 34: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

34

OverridingOverriding

If a method is declared with the If a method is declared with the finalfinal modifier, it cannot modifier, it cannot be overriddenbe overridden

The concept of overriding can be applied to data and is The concept of overriding can be applied to data and is called called shadowing variablesshadowing variables

Shadowing variables should be avoided because it tends to Shadowing variables should be avoided because it tends to cause unnecessarily confusing codecause unnecessarily confusing code

Page 35: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

35

The The supersuper Reference Revisited Reference Revisited

A method in the parent class can be invoked explicitly A method in the parent class can be invoked explicitly using the using the supersuper reference reference

The The supersuper reference can be used to invoke any method reference can be used to invoke any method from the parent class.from the parent class.

This ability is often helpful when using overridden methodsThis ability is often helpful when using overridden methods

The syntax is:The syntax is: super.super.methodmethod((parametersparameters))

See See Accounts.javaAccounts.java

Page 36: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

36

SubClassesSubClasses

When we extend an existing class, we 'inherit' all of the When we extend an existing class, we 'inherit' all of the attributes, and methods, of the parent class. attributes, and methods, of the parent class.

In the Accounts.java program, the child class can deposit, In the Accounts.java program, the child class can deposit, and withdraw - even though we only explicitly define a and withdraw - even though we only explicitly define a new method for new method for withdrawal.withdrawal.

This makes programming much easier, and simpler, as we This makes programming much easier, and simpler, as we don't re-invent the wheel each time we extend other don't re-invent the wheel each time we extend other classes. classes.

In the example above, we add two new methods , and call In the example above, we add two new methods , and call the constructor of our parent class. the constructor of our parent class.

Page 37: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

37

Class HierarchiesClass Hierarchies

Two children of the same parent are called Two children of the same parent are called siblings.siblings.

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

Class hierarchies often have to be extended and modified Class hierarchies often have to be extended and modified to keep up with changing needsto keep up with changing needs

There is no single class hierarchy that is appropriate for There is no single class hierarchy that is appropriate for all situationsall situations

Page 38: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

38

Single vs. Multiple InheritanceSingle vs. Multiple Inheritance

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

Multiple inheritanceMultiple inheritance allows a class to be derived from two or allows a class to be derived from two or more classes, inheriting the members of all parentsmore classes, inheriting the members of all parents

Collisions, such as the same variable name in two parents, have Collisions, such as the same variable name in two parents, have to be resolvedto be resolved

In most cases, the use of interfaces gives us the best aspects of In most cases, the use of interfaces gives us the best aspects of multiple inheritance without the overheadmultiple inheritance without the overhead

Page 39: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

39

Class HierarchiesClass Hierarchies

A child class of one parent can be the parent of another A child class of one parent can be the parent of another child, forming child, forming class hierarchiesclass hierarchies

Business

RetailBusiness ServiceBusiness

KMart Macys Penny’s

Page 40: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

40

The The ObjectObject Class Class

A class called A class called ObjectObject is defined in the is defined in the java.langjava.lang package of the Java standard class librarypackage of the Java standard class library

All classes are derived from the All classes are derived from the ObjectObject class class

If a class is not explicitly defined to be the child of an If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the existing class, it is assumed to be the child of the ObjectObject classclass

The The ObjectObject class is therefore the ultimate root of all class class is therefore the ultimate root of all class hierarchieshierarchies

Page 41: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

41

The The ObjectObject Class Class

The The ObjectObject class contains a few useful methods, which are class contains a few useful methods, which are inherited by all classesinherited by all classes

For example, the For example, the toStringtoString method is defined in the method is defined in the ObjectObject class class

Every time we have defined Every time we have defined toStringtoString, we have actually , we have actually been overriding itbeen overriding it

The The toStringtoString method in the method in the ObjectObject class is defined to class is defined to return a string that contains the name of the object’s class return a string that contains the name of the object’s class and a hash valueand a hash value

Page 42: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

42

Class ObjectClass Object

The class Object defines the following methods: The class Object defines the following methods: • clone()clone()• equals(Object obj)equals(Object obj)• finalize()finalize()• getClass()getClass()• hashCode()hashCode()• notify()notify()• notifyAll()notifyAll()• toString()toString()• wait()wait()• wait(long timeout)wait(long timeout)• wait(long timeout, int nanos) wait(long timeout, int nanos) 

As you can see, this list includes three overloaded versions As you can see, this list includes three overloaded versions of the method named wait (same name, different formal of the method named wait (same name, different formal argument lists). argument lists).

Page 43: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

43

Class ObjectClass Object

Because every class is either a direct or indirect subclass of Because every class is either a direct or indirect subclass of Object, every class in Java, (including new classes that you Object, every class in Java, (including new classes that you define), inherit these eleven methods. define), inherit these eleven methods.

   Generally speaking, many of these eleven methods are Generally speaking, many of these eleven methods are

intended to be overridden for various purposes. intended to be overridden for various purposes.

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

  

Page 44: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

44

The The ObjectObject Class Class

That’s why the That’s why the printlnprintln method can call method can call toStringtoString for for any object that is passed to it – all objects are guaranteed to any object that is passed to it – all objects are guaranteed to have a have a toStringtoString method via inheritance method via inheritance

See Academia.java See Academia.java See Student.java See Student.java See GradStudent.java See GradStudent.java

The equals method of the Object class determines if two The equals method of the Object class determines if two references are aliasesreferences are aliases

You may choose to override You may choose to override equalsequals to define equality in to define equality in some other way some other way

Page 45: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

45

References and InheritanceReferences and Inheritance

Assigning a predecessor object to an ancestor reference is Assigning a predecessor object to an ancestor reference is considered to be a widening conversion, and can be considered to be a widening conversion, and can be performed by simple assignmentperformed by simple assignment

Assigning an ancestor object to a predecessor reference can Assigning an ancestor object to a predecessor reference can also be done, but it is considered to be a narrowing also be done, but it is considered to be a narrowing conversion and must be done with a castconversion and must be done with a cast

The widening conversion is the most usefulThe widening conversion is the most useful

Page 46: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

46

PolymorphismPolymorphism

What is polymorphism?What is polymorphism?

The meaning of the word polymorphism is something like The meaning of the word polymorphism is something like one name, many forms. one name, many forms.

   How does Java implement polymorphism?How does Java implement polymorphism?

   Polymorphism manifests itself in Java in the form of Polymorphism manifests itself in Java in the form of

multiple methods having the same name. multiple methods having the same name.

  

Page 47: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

47

PolymorphismPolymorphism

In some cases, multiple methods have the same name, but In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). different formal argument lists (overloaded methods).

•    In other cases, multiple methods have the same name, same In other cases, multiple methods have the same name, same

return type, and same formal argument list (overridden return type, and same formal argument list (overridden methods). methods).

Three distinct forms of polymorphismThree distinct forms of polymorphism   Method overloadingMethod overloading Method overriding through inheritanceMethod overriding through inheritance Method overriding through the Java interfaceMethod overriding through the Java interface

Page 48: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

48

Polymorphism via InheritancePolymorphism via Inheritance

A A polymorphic referencepolymorphic reference is one which can refer to different is one which can refer to different types of objects at different times.types of objects at different times.

InheritanceInheritance can also be used as a basis of polymorphism can also be used as a basis of polymorphism

An object reference can refer to one object at one time, An object reference can refer to one object at one time, then it can be changed to refer to another object (related by then it can be changed to refer to another object (related by inheritance) at another timeinheritance) at another time

Page 49: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

49

Polymorphism via InheritancePolymorphism via Inheritance

Suppose the Suppose the HolidayHoliday class has a method called class has a method called celebratecelebrate, and the , and the ChristmasChristmas class overrode it class overrode it

Now consider the following invocation:Now consider the following invocation:

day.celebrate();

If If dayday refers to a refers to a HolidayHoliday object object, it invokes the , it invokes the HolidayHoliday version of version of celebratecelebrate; if it refers to a ; if it refers to a ChristmasChristmas object, object, it invokes the it invokes the ChristmasChristmas version version

Page 50: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

50

InheritanceInheritance

Accounts[] customer= new Accounts[10]; Accounts[] customer= new Accounts[10];

Senior_Savings Sam = new Senior_Savings(“Sam”); Senior_Savings Sam = new Senior_Savings(“Sam”);

customer[5] = Sam;customer[5] = Sam;

Accounts Ricky = new Accounts(“Ricky”);Accounts Ricky = new Accounts(“Ricky”);

customer[3] = Ricky;customer[3] = Ricky;

So the array So the array customer customer of class of class Accounts Accounts holds both holds both Senior-Senior-SavingsSavings and regular and regular Accounts.Accounts.

Page 51: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

51

PolymorphismPolymorphism

The Senior_Savings class overrides the Account class The Senior_Savings class overrides the Account class methodmethod depositdeposit with a with a depositdeposit method of its own. method of its own.

We assign a position in the customer accounts array We assign a position in the customer accounts array (which is an array of Customer accounts) to a (which is an array of Customer accounts) to a Senior_Savings account. Senior_Savings account.

So the customer holds both regular customer accounts So the customer holds both regular customer accounts and Senior_Savings accounts.and Senior_Savings accounts.

The deposit method that is called depends on what type The deposit method that is called depends on what type of object is in the array.of object is in the array.

Page 52: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

52

Class BankClass Bank

public class Bank public class Bank {{public static void main(String args[]) {public static void main(String args[]) {    Account [] customer = new Account[10]; Account [] customer = new Account[10]; for (int i=0; i< 3; i++) { for (int i=0; i< 3; i++) { System.out.print ("Name of customer:); System.out.print ("Name of customer:); String name = scan.next(); String name = scan.next(); System.out.print ("Type of Account: S for Senior, R for regular "); System.out.print ("Type of Account: S for Senior, R for regular ");

    String type = scan.next(); String type = scan.next();     acctype = type.charAt(0);acctype = type.charAt(0); if(acctype == 'S'){ if(acctype == 'S'){ customer[i] = new Senior_Savings(Name, acctype, accountnumber++); customer[i] = new Senior_Savings(Name, acctype, accountnumber++);

} } else else if (acctype == 'R’)if (acctype == 'R’)

customer[i] = new Account(Name, acctype, accountnumber++); customer[i] = new Account(Name, acctype, accountnumber++);

  } // close for} // close for  

Page 53: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

53

Class AccountClass Account

When we call the deposit method in a loop , the deposit When we call the deposit method in a loop , the deposit method that is called depends on whether the object in the method that is called depends on whether the object in the array is of the Account class or the Senior_Savings class. array is of the Account class or the Senior_Savings class.

if(acctype == 'S')if(acctype == 'S')

{ customer{ customer[i] = new SeniorSavings([i] = new SeniorSavings(name, acctype, accnum++); name, acctype, accnum++);

customer[i].deposit(45); customer[i].deposit(45); } } else else if (acctype == 'R’)if (acctype == 'R’)

{{

customer [i] = new Account(name, acctype, acctnum++); customer [i] = new Account(name, acctype, acctnum++);

customer[i].deposit(75); customer[i].deposit(75); } }

Page 54: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

54

PolymorphismPolymorphism

In general, it is the type of the object being referenced In general, it is the type of the object being referenced determines which method is invoked.determines which method is invoked.

Objects of Objects of Thought Thought class and class and AdviceAdvice class are class are

instantiated. They both contain a method called message. instantiated. They both contain a method called message.

Initially, they each call their respective methods. Then the Initially, they each call their respective methods. Then the Thought object is assigned the value of the advice object.Thought object is assigned the value of the advice object.

Page 55: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

55

PolymorphismPolymorphism

When the When the messagemessage method is invoked by the method is invoked by the ThoughtThought object, object, the the adviceadvice version is executed. version is executed.

Note that, if an invocation is in a loop, the exact same line of Note that, if an invocation is in a loop, the exact same line of code could execute different methods at different times. code could execute different methods at different times.

Polymorphic references are therefore resolved at run-time, not Polymorphic references are therefore resolved at run-time, not during compilationduring compilation

Page 56: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

56

PolymorphismPolymorphism Note that, because all classes inherit from the Note that, because all classes inherit from the ObjectObject

class, an class, an ObjectObject reference can refer to any type of reference can refer to any type of object .object .

A A ArrayListArrayList is designed to store is designed to store ObjectObject references references of any type.of any type.

The The instanceOfinstanceOf operator can be used to determine operator can be used to determine the class from which an object was createdthe class from which an object was created

Page 57: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

57

Variety. javaVariety. java

public static void main (String[] args) {public static void main (String[] args) {    // create a vector called collector // create a vector called collector ArrayList collector = new ArrayLIst();ArrayList collector = new ArrayLIst(); // create an integer object num1// create an integer object num1 Integer num1 = new Integer (10);Integer num1 = new Integer (10); collector.add(num1);collector.add(num1);

  // create an point object, origin// create an point object, origin    Point origin = new Point (0, 0);Point origin = new Point (0, 0); collector.add(origin);collector.add(origin);  // create an integer object and store it in the vector// create an integer object and store it in the vector Integer num2 = new Integer (37);Integer num2 = new Integer (37); collector.add (num2);collector.add (num2);  

Page 58: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

58

Variety ProgramVariety Program

int temp;int temp;    Object someObject;Object someObject;

    for (int count=0; count < 4; count++) {for (int count=0; count < 4; count++) {    someObject = collector.elementAt (count);someObject = collector.elementAt (count); if (someObject instanceof Integer) {if (someObject instanceof Integer) { temp = ((Integer)someObject).intValue() + 20;temp = ((Integer)someObject).intValue() + 20; System.out.println (something + " + 20 = System.out.println (something + " + 20 =

" + temp);" + temp);

} else} else System.out.println ("Point: " + something);System.out.println ("Point: " + something); } } } // method main} // method main

Page 59: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

59

Variety.javaVariety.java

In the Variety program, while iterating through a loop different In the Variety program, while iterating through a loop different objects as assigned to an object which is defined as; objects as assigned to an object which is defined as;

someObject = collector.elementAt(count);someObject = collector.elementAt(count);

if (someObject.instanceof Integer){if (someObject.instanceof Integer){

Polymorphism means that the sender of a message does not Polymorphism means that the sender of a message does not need to to be aware of which class the receiving object belongs need to to be aware of which class the receiving object belongs to. to.

The receiving instance can belong to an any classThe receiving instance can belong to an any class

Page 60: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

60

PolymorphismPolymorphism

A sender object needs only to know that another object can perform a A sender object needs only to know that another object can perform a certain behavior, not which class it belongs to nor which operations certain behavior, not which class it belongs to nor which operations will perform that behavior.will perform that behavior.

Flexible systems can thus be implemented. Flexible systems can thus be implemented.

When a new object from a new class is added, this modification When a new object from a new class is added, this modification should only affect this new object not those who send messages to itshould only affect this new object not those who send messages to it

Page 61: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

61

Indirect AccessIndirect Access

An inherited member can be referenced directly by name An inherited member can be referenced directly by name in the child class, as if it were declared in the child classin the child class, as if it were declared in the child class

But even if a method or variable is not inherited by a child, But even if a method or variable is not inherited by a child, it can still be accessed indirectly through parent methodsit can still be accessed indirectly through parent methods

See FoodAnalysis.java (page 355)See FoodAnalysis.java (page 355) See FoodItem.java (page 356)See FoodItem.java (page 356) See Pizza.java (page 357)See Pizza.java (page 357)

Page 62: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

62

Final MethodsFinal Methods

A final method cannot be overridden.

Declaring a method final prevents the derived class from erroneously redefining a class method.

Declaring a method final allows the compiler to perform inline optimization.

final classes cannot be extended.

Page 63: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

63

Abstract ClassesAbstract Classes

An abstract class is a placeholder in a class hierarchy that An abstract class is a placeholder in a class hierarchy that represents a generic conceptrepresents a generic concept

An abstract class cannot be instantiatedAn abstract class cannot be instantiated

We use the modifier We use the modifier abstractabstract on the class header to on the class header to declare a class as abstractdeclare a class as abstract

An abstract class often contains abstract methods (like an An abstract class often contains abstract methods (like an interface does), though it doesn’t have tointerface does), though it doesn’t have to

Page 64: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

64

Abstract ClassesAbstract Classes

An An abstract classabstract class is a placeholder in a class hierarchy that is a placeholder in a class hierarchy that represents a generic conceptrepresents a generic concept

An abstract class cannot be instantiatedAn abstract class cannot be instantiated

We use the modifier We use the modifier abstractabstract on the class header to on the class header to declare a class as abstract:declare a class as abstract:

public abstract class Productpublic abstract class Product

{{

// contents// contents

}}

Page 65: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

65

Abstract ClassesAbstract Classes

An abstract class often contains abstract methods with An abstract class often contains abstract methods with no definitions (like an interface)no definitions (like an interface)

Unlike an interface, the Unlike an interface, the abstractabstract modifier must be modifier must be applied to each abstract methodapplied to each abstract method

Also, an abstract class typically contains non-abstract Also, an abstract class typically contains non-abstract methods with full definitionsmethods with full definitions

A class declared as abstract does not have to contain A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes abstract methods -- simply declaring it as abstract makes it soit so

Page 66: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

66

Abstract ClassesAbstract Classes

The child of an abstract class must override the abstract The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstractmethods of the parent, or it too will be considered abstract

An abstract method cannot be defined as An abstract method cannot be defined as finalfinal or or staticstatic

The use of abstract classes is an important element of The use of abstract classes is an important element of software design – it allows us to establish common elements software design – it allows us to establish common elements in a hierarchy that are too generic to instantiatein a hierarchy that are too generic to instantiate

Page 67: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

67

Interface HierarchiesInterface Hierarchies

Inheritance can be applied to interfaces as well as classesInheritance can be applied to interfaces as well as classes

That is, one interface can be derived from another That is, one interface can be derived from another interfaceinterface

The child interface inherits all abstract methods of the The child interface inherits all abstract methods of the parentparent

A class implementing the child interface must define all A class implementing the child interface must define all methods from both the ancestor and child interfacesmethods from both the ancestor and child interfaces

Note that class hierarchies and interface hierarchies are Note that class hierarchies and interface hierarchies are distinct (they do not overlap)distinct (they do not overlap)

Page 68: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

68

Abstract ClassesAbstract Classes

The child of an abstract class must override the abstract The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstractmethods of the parent, or it too will be considered abstract

An abstract method cannot be defined as final (because it An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition must be overridden) or static (because it has no definition yet)yet)

The use of abstract classes is a design decision; it helps us The use of abstract classes is a design decision; it helps us establish common elements in a class that is to general to establish common elements in a class that is to general to instantiateinstantiate

Page 69: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

69

Applets and InheritanceApplets and Inheritance

An applet is an excellent example of inheritanceAn applet is an excellent example of inheritance

Recall that when we define an applet, we extend the Recall that when we define an applet, we extend the AppletApplet class class

The The AppletApplet class already handles all the details about class already handles all the details about applet creation and execution, including the interaction applet creation and execution, including the interaction with a web browserwith a web browser

Our applet classes only have to deal with issues that Our applet classes only have to deal with issues that specifically relate to what our particular applet will dospecifically relate to what our particular applet will do

Page 70: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

70

Extending Event Adapter Extending Event Adapter ClassesClasses

The creation of listener classes is done by implementing a The creation of listener classes is done by implementing a particular interface (such as particular interface (such as MouseListenerMouseListener interface) interface)

A listener can also be created by extending a special A listener can also be created by extending a special adapter adapter classclass of the Java class library of the Java class library

Each listener interface has a corresponding adapter class Each listener interface has a corresponding adapter class (such as the (such as the MouseAdapterMouseAdapter class) class)

Each adapter class implements the corresponding listener Each adapter class implements the corresponding listener and provides empty method definitionsand provides empty method definitions

Page 71: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

71

Extending Event Adapter Extending Event Adapter ClassesClasses

When you derive a listener class from an adapter class, you When you derive a listener class from an adapter class, you override any event methods of interest (such as the override any event methods of interest (such as the mouseClickedmouseClicked method) method)

Note that this avoids the need to create empty definitions Note that this avoids the need to create empty definitions for unused eventsfor unused events

See OffCenter.java (page 360)See OffCenter.java (page 360)

Page 72: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

72

GUI ComponentsGUI Components

A A GUI componentGUI component is an object that represents a visual is an object that represents a visual entity in an graphical user interface (such as a button or entity in an graphical user interface (such as a button or slider)slider)

Components can generate events to which listener objects Components can generate events to which listener objects can respondcan respond

For example, an applet is a component that can generate For example, an applet is a component that can generate mouse eventsmouse events

An applet is also a special kind of component, called a An applet is also a special kind of component, called a containercontainer, in which other components can be placed, in which other components can be placed

Page 73: 1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

73

GUI ComponentsGUI Components

See Fahrenheit.java (page 363)See Fahrenheit.java (page 363)

Components are organized into an inheritance class Components are organized into an inheritance class hierarchy so that they can easily share characteristicshierarchy so that they can easily share characteristics

When we define certain methods, such as the When we define certain methods, such as the paintpaint method of an applet, we are actually overriding a method method of an applet, we are actually overriding a method defined in the defined in the ComponentComponent class, which is ultimately class, which is ultimately inherited into the inherited into the AppletApplet class class

See Doodle.java (page 367)See Doodle.java (page 367) See DoodleCanvas.java (page 369)See DoodleCanvas.java (page 369)