inheritance and class hierarchies · all java classes are arranged in a hierarchy, starting with...

45
Inheritance and Class Hierarchies Inheritance and Class Hierarchies Chapter 3 Chapter 3

Upload: others

Post on 21-May-2020

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Inheritance and Class HierarchiesInheritance and Class Hierarchies

Chapter 3Chapter 3

Page 2: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Chapter ObjectivesChapter Objectives

To understand inheritance and how it facilitates code reuseTo understand how Java determines which method to execute when there are multiple methods with the same name in a class hierarchyTo learn how to define and use abstract classes as base classes in a hierarchyTo study class Object and its methods and to learn how to override themTo learn how to “clone” an object and to understand the difference between a true clone (deep copy) and a shallow copy

To understand inheritance and how it facilitates code reuseTo understand how Java determines which method to execute when there are multiple methods with the same name in a class hierarchyTo learn how to define and use abstract classes as base classes in a hierarchyTo study class Object and its methods and to learn how to override themTo learn how to “clone” an object and to understand the difference between a true clone (deep copy) and a shallow copy

Page 3: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Chapter Objectives (continued)Chapter Objectives (continued)

To understand why Java does not implement multiple inheritance and to see how you can gain some of the advantages of multiple inheritance through interfaces and delegationTo become familiar with a class hierarchy for drawable shapesTo be introduced to an object factory and to learn how to use itTo understand how to create packages and to learn more about visibility

To understand why Java does not implement multiple inheritance and to see how you can gain some of the advantages of multiple inheritance through interfaces and delegationTo become familiar with a class hierarchy for drawable shapesTo be introduced to an object factory and to learn how to use itTo understand how to create packages and to learn more about visibility

Page 4: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Introduction to Inheritance and Class Hierarchies

Introduction to Inheritance and Class Hierarchies

Popularity of OOP is that it enables programmers to reuse previously written code saved as classesAll Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classesInheritance in OOP is analogous to inheritance in humansInheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another

Popularity of OOP is that it enables programmers to reuse previously written code saved as classesAll Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classesInheritance in OOP is analogous to inheritance in humansInheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another

Page 5: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous
Page 6: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Is-a Versus Has-a RelationshipsIs-a Versus Has-a Relationships

One misuse of inheritance is confusing the has-a relationship with the is-a relationshipThe has-a relationship means that one class has the second class as an attributeWe can combine is-a and has-a relationshipsThe keyword extends specifies that one class is a subclass of another

One misuse of inheritance is confusing the has-a relationship with the is-a relationshipThe has-a relationship means that one class has the second class as an attributeWe can combine is-a and has-a relationshipsThe keyword extends specifies that one class is a subclass of another

Page 7: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

A Superclass and a SubclassA Superclass and a Subclass

Consider two classes: Computer and LaptopA laptop is a kind of computer and is therefore a subclass of computer

Consider two classes: Computer and LaptopA laptop is a kind of computer and is therefore a subclass of computer

Page 8: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Initializing Data Fields in a Subclass and the No-Parameter

Constructor

Initializing Data Fields in a Subclass and the No-Parameter

ConstructorPrivate data fields belonging to a base class must be initialized by invoking the base class’s constructor with the appropriate parametersIf the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclass

Initializes that part of the object inherited from the superclass before the subclass starts to initialize its part of the object

Private data fields belonging to a base class must be initialized by invoking the base class’s constructor with the appropriate parametersIf the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclass

Initializes that part of the object inherited from the superclass before the subclass starts to initialize its part of the object

Page 9: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Protected Visibility for Superclass Data Fields

Protected Visibility for Superclass Data Fields

Private data fields are not accessible to derived classesProtected visibility allows data fields to be accessed either by the class defining it or any subclassIn general, it is better to use private visibility because subclasses may be written by different programmers and it is always good practice to restrict and control access to the superclass data fields

Private data fields are not accessible to derived classesProtected visibility allows data fields to be accessed either by the class defining it or any subclassIn general, it is better to use private visibility because subclasses may be written by different programmers and it is always good practice to restrict and control access to the superclass data fields

Page 10: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Method OverridingMethod Overriding

If a derived class has a method found within its base class, that method will override the base class’s methodThe keyword super can be used to gain access to superclass methods overridden by the base classA subclass method must have the same return type as the corresponding superclass method

If a derived class has a method found within its base class, that method will override the base class’s methodThe keyword super can be used to gain access to superclass methods overridden by the base classA subclass method must have the same return type as the corresponding superclass method

Page 11: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Method OverloadingMethod Overloading

Method overloading: having multiple methods with the same name but different signatures in a classConstructors are often overloadedExample:

MyClass(int inputA, int inputB)MyClass(int inputA, int inputB, double inputC)

Method overloading: having multiple methods with the same name but different signatures in a classConstructors are often overloadedExample:

MyClass(int inputA, int inputB)MyClass(int inputA, int inputB, double inputC)

Page 12: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

PolymorphismPolymorphism

A variable of a superclass type can reference an object of a subclass typePolymorphism means many forms or many shapesPolymorphism allows the JVM to determine which method to invoke at run timeAt compile time, the Java compiler can’t determine what type of object a superclass may reference but it is known at run time

A variable of a superclass type can reference an object of a subclass typePolymorphism means many forms or many shapesPolymorphism allows the JVM to determine which method to invoke at run timeAt compile time, the Java compiler can’t determine what type of object a superclass may reference but it is known at run time

Page 13: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Abstract Classes, Assignment, and Casting in a Hierarchy

Abstract Classes, Assignment, and Casting in a Hierarchy

An interface can declare methods but does not provide an implementation of those methods

Methods declared in an interface are called abstract methods

An abstract class can have abstract methods, data fields, and concrete methodsAbstract class differs from a concrete class in that

An abstract class cannot be instantiatedAn abstract class can declare abstract methods, which must be implemented in its subclasses

An interface can declare methods but does not provide an implementation of those methods

Methods declared in an interface are called abstract methods

An abstract class can have abstract methods, data fields, and concrete methodsAbstract class differs from a concrete class in that

An abstract class cannot be instantiatedAn abstract class can declare abstract methods, which must be implemented in its subclasses

Page 14: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Abstract Classes and InterfacesAbstract Classes and Interfaces

Like an interface, an abstract class can’t be instantiatedAn abstract class can have constructors to initialize its data fields when a new subclass is created

Subclass uses super(…) to call the constructorMay implement an interface but it doesn’t have to define all of the methods declared in the interface

Implementation is left to its subclasses

Like an interface, an abstract class can’t be instantiatedAn abstract class can have constructors to initialize its data fields when a new subclass is created

Subclass uses super(…) to call the constructorMay implement an interface but it doesn’t have to define all of the methods declared in the interface

Implementation is left to its subclasses

Page 15: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Abstract Class Number and the Java Wrapper Classes

Abstract Class Number and the Java Wrapper Classes

Page 16: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Summary of Features of Actual Classes, Abstract Classes, and

Interfaces

Summary of Features of Actual Classes, Abstract Classes, and

Interfaces

Page 17: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Class Object, Casting and CloningClass Object, Casting and Cloning

Object is the root of the class hierarchy; every class has Object as a superclassAll classes inherit the methods defined in class Object but may be overridden

Object is the root of the class hierarchy; every class has Object as a superclassAll classes inherit the methods defined in class Object but may be overridden

Page 18: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

The Method toStringThe Method toString

You should always override the toString method if you want to represent an object’s stateIf you do not override it, the toString method for class Object will return a string…just not the string you want or are expecting

You should always override the toString method if you want to represent an object’s stateIf you do not override it, the toString method for class Object will return a string…just not the string you want or are expecting

Page 19: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Operations Determined by Type of Reference Variable

Operations Determined by Type of Reference Variable

A variable can reference an object whose type is a subclass of the variable typeThe type of reference, not the type of the object referenced, determines what operations can be performedJava is a strongly typed language so the compiler always verifies that the type of the expression being assigned is compatible with the variable type

A variable can reference an object whose type is a subclass of the variable typeThe type of reference, not the type of the object referenced, determines what operations can be performedJava is a strongly typed language so the compiler always verifies that the type of the expression being assigned is compatible with the variable type

Page 20: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Casting in a Class HierarchyCasting in a Class Hierarchy

Java provides casting to enable us to process one object referenced by one type through a reference variable of its actual typeCasting does not change the object referenced; it creates an anonymous reference to that objectDowncast: cast a higher type to a lower typeThe instanceof operator can guard against ClassCastException errorsYou can downcast an interface reference to the specific implementation type

Java provides casting to enable us to process one object referenced by one type through a reference variable of its actual typeCasting does not change the object referenced; it creates an anonymous reference to that objectDowncast: cast a higher type to a lower typeThe instanceof operator can guard against ClassCastException errorsYou can downcast an interface reference to the specific implementation type

Page 21: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Java 5.0 Reduces Need for CastingJava 5.0 Reduces Need for Casting

Two new features that reduce the need for casting:Autoboxing/unboxingGenerics

Autoboxing/unboxing eases the conversion between a primitive type and its corresponding wrapper type

Two new features that reduce the need for casting:Autoboxing/unboxingGenerics

Autoboxing/unboxing eases the conversion between a primitive type and its corresponding wrapper type

Page 22: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

The Method Object.equalsThe Method Object.equals

The Object.equals method has a parameter of type ObjectCompares two objects to determine whether they are equalYou must override the equals method if you want to be able to compare two objects of a class

The Object.equals method has a parameter of type ObjectCompares two objects to determine whether they are equalYou must override the equals method if you want to be able to compare two objects of a class

Page 23: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

CloningCloning

The purpose of cloning in object-oriented programming is analogous to cloning in biology

Create an independent copy of an objectInitially, both objects will store the same informationYou can change one object without affecting the other

Will cause both e1.name and e2.name to reference “Jim”

The purpose of cloning in object-oriented programming is analogous to cloning in biology

Create an independent copy of an objectInitially, both objects will store the same informationYou can change one object without affecting the other

Will cause both e1.name and e2.name to reference “Jim”

Page 24: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

The Shallow Copy ProblemThe Shallow Copy Problem

Page 25: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

The statement e1.setAddressLine1("Room 224"); creates a new String object that is referenced by e1.address.line1 and e2.address.line1

The statement e1.setAddressLine1("Room 224"); creates a new String object that is referenced by e1.address.line1 and e2.address.line1

Page 26: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

The Object.clone methodThe Object.clone method

Java provides the Object.clone method to help solve the shallow copy problemThe initial copy is a shallow copy as the current object’s data fields are copiedTo make a deep copy, you must create cloned copies of all components by invoking their respective clone methods

Java provides the Object.clone method to help solve the shallow copy problemThe initial copy is a shallow copy as the current object’s data fields are copiedTo make a deep copy, you must create cloned copies of all components by invoking their respective clone methods

Page 27: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

The Object.clone method (continued)

The Object.clone method (continued)

After e1.setAddressLine1("Room 224"); only e1.address.line1 references the new String object. After e1.setAddressLine1("Room 224"); only e1.address.line1 references the new String object.

Page 28: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Employee.clone()Employee.clone()

Page 29: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Address.clone()Address.clone()

Page 30: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Multiple Inheritance, Multiple Interfaces, and Delegation

Multiple Inheritance, Multiple Interfaces, and Delegation

Multiple inheritance: the ability to extend more than one classMultiple inheritance is a language feature that is difficult to implement and can lead to ambiguity

Therefore, Java does not allow a class to extend more than one class

Multiple inheritance: the ability to extend more than one classMultiple inheritance is a language feature that is difficult to implement and can lead to ambiguity

Therefore, Java does not allow a class to extend more than one class

Page 31: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Using Multiple Interfaces to Emulate Multiple InheritanceUsing Multiple Interfaces to Emulate Multiple Inheritance

If we define two interfaces, a class can implement bothMultiple interfaces emulate multiple inheritanceIf we define two interfaces, a class can implement bothMultiple interfaces emulate multiple inheritance

Page 32: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Using Multiple Interfaces to Emulate Multiple Inheritance

(continued)

Using Multiple Interfaces to Emulate Multiple Inheritance

(continued)

Page 33: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Implementing Reuse Through Delegation

Implementing Reuse Through Delegation

You can reduce duplication of modifications and reduce problems associated with version control through a technique known as delegationIn delegation, a method of one class accomplishes an operation by delegating it to a method of another class

You can reduce duplication of modifications and reduce problems associated with version control through a technique known as delegationIn delegation, a method of one class accomplishes an operation by delegating it to a method of another class

Page 34: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

PackagesPackages

The Java API is organized into packagesThe package to which a class belongs is declared by the first statement in the file in which the class is defined using the keyword package followed by the package nameAll classes in the same package are stored in the same directory or folderAll the classes in one folder must declare themselves to be in the same packageClasses that are not part of a package may access only public members of classes in the package

The Java API is organized into packagesThe package to which a class belongs is declared by the first statement in the file in which the class is defined using the keyword package followed by the package nameAll classes in the same package are stored in the same directory or folderAll the classes in one folder must declare themselves to be in the same packageClasses that are not part of a package may access only public members of classes in the package

Page 35: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

The No-Package-Declared Environment and Package Visibility

The No-Package-Declared Environment and Package Visibility

There exists a default packageFiles that do specify a package are considered part of the default package

If you don’t declare packages, all of your packages belong to the same, default packagePackage visibility sits between private and protected

Classes, data fields, and methods with package visibility are accessible to all other methods of the same package but are not accessible to methods outside of the packageClasses, data fields, and methods that are declared protected are visible to all members of the package

There exists a default packageFiles that do specify a package are considered part of the default package

If you don’t declare packages, all of your packages belong to the same, default packagePackage visibility sits between private and protected

Classes, data fields, and methods with package visibility are accessible to all other methods of the same package but are not accessible to methods outside of the packageClasses, data fields, and methods that are declared protected are visible to all members of the package

Page 36: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Visibility Supports EncapsulationVisibility Supports Encapsulation

The rules for visibility control how encapsulation occurs in a Java programPrivate visibility is for members of a class that should not be accessible to anyone but the class, not even the classes that extend itPackage visibility allows the developer of a library to shield classes and class members from classes outside the packageUse of protected visibility allows the package developer to give control to other programmers who want to extend classes in the package

The rules for visibility control how encapsulation occurs in a Java programPrivate visibility is for members of a class that should not be accessible to anyone but the class, not even the classes that extend itPackage visibility allows the developer of a library to shield classes and class members from classes outside the packageUse of protected visibility allows the package developer to give control to other programmers who want to extend classes in the package

Page 37: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Table 3.3Table 3.3Private Visibility

Classes : Applicable to inner classes. Accessible only to members of the class in which it is declared.Class Members: Visible only within this class.

Default (or package) VisibilityClasses : Visible to classes in this package.Class Members : Visible to classes in this package.

Protected VisibilityClasses : Applicable to inner classes. Visible to classes in this package and to classes outside the package that extend the class in which it is declared.Class Members : Visible to classes in this package and to classes outside the package that extend this class.

Public Visibility Classes: Visible to all classes.Class Members : Visible to all classes. The class defining the member must also be public.

Private VisibilityClasses : Applicable to inner classes. Accessible only to members of the class in which it is declared.Class Members: Visible only within this class.

Default (or package) VisibilityClasses : Visible to classes in this package.Class Members : Visible to classes in this package.

Protected VisibilityClasses : Applicable to inner classes. Visible to classes in this package and to classes outside the package that extend the class in which it is declared.Class Members : Visible to classes in this package and to classes outside the package that extend this class.

Public Visibility Classes: Visible to all classes.Class Members : Visible to all classes. The class defining the member must also be public.

Page 38: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Visibility Supports Encapsulation (continued)

Visibility Supports Encapsulation (continued)

Page 39: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

A Shape Class HierarchyA Shape Class Hierarchy

Page 40: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

A Shape Class Hierarchy (continued)

A Shape Class Hierarchy (continued)

Page 41: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous
Page 42: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

A Shape Class Hierarchy (continued)

A Shape Class Hierarchy (continued)

Page 43: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Object FactoriesObject Factories

An object factory is a method that creates instances of other classesObject factories are useful when:

The necessary parameters are not known or must be derived via computationThe appropriate implementation of an interface or abstract class should be selected as the result of some computation

An object factory is a method that creates instances of other classesObject factories are useful when:

The necessary parameters are not known or must be derived via computationThe appropriate implementation of an interface or abstract class should be selected as the result of some computation

Page 44: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Object Factories (continued)Object Factories (continued)

Page 45: Inheritance and Class Hierarchies · All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous

Chapter ReviewChapter Review

Inheritance and class hierarchies to capture the idea that one thing may be a refinement or extension of anotherEncapsulation and inheritance impose structure on object abstractionsThe keyword interface defines an interfaceThe keyword abstract defines an abstract class or methodDelegation gains some of the advantages of multiple inheritanceVisibility is influenced by the package in which a class is declared

Inheritance and class hierarchies to capture the idea that one thing may be a refinement or extension of anotherEncapsulation and inheritance impose structure on object abstractionsThe keyword interface defines an interfaceThe keyword abstract defines an abstract class or methodDelegation gains some of the advantages of multiple inheritanceVisibility is influenced by the package in which a class is declared