Transcript Chapter 3

Chapter 3
Inheritance
© 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Overview
●
●
3.1 Extending a class
–
How and when to create a subclass that inherits code from
the class (superclass) it extends.
–
A better solution is to use inheritance.
3.2 The Object class
–
●
3.3 Packages and Access Levels
–
●
Object class, from which all other classes are ultimately
derived.
Packages (collections of classes) and access levels, which
give us finer control over who can see which parts of our
classes.
Refer to http://www.tutorialspoint.com/java/java_inheritance.htm
Extending a Class
●
●
The Cram game is identical to Domineering
except that a player can play each domino
either horizontally or vertically.
–
Should we write a new program that looks very
similar to the old one? The answer is no.
–
Use inheritance.
Cram extends Domineering.
–
New class specifies only the things that are
different.
Extending a Class
Extending a Class
Extending a Class
●
Cram is called a subclass of Domineering.
●
Domineering is a superclass of Cram.
Extending a Class
●
Fields and methods not listed in the code for
the Cram class are inherited from the
Domineering class.
–
If we invoke playAt() or hasLegalMoveFor() the
method from the Domineering class is used.
–
The Cram class does override two methods,
play() and main().
–
Additional fields and methods, along with
overridden methods, make a Cram instance
different from a Domineering instance.
Extending a Class
●
When we override a method, Java decides
which version to use based on the object on
which the method is invoked.
–
The invocation super(); in a constructor means
“do whatever you would do to set up an instance
of the parent class”.
–
A constructor in a subclass must always begin by
invoking a constructor from the class it extends,
although, this invocation can often be implicit.
Extending a Class
●
●
Inheritance allows us to extend an
encapsulated class without thinking about its
inner workings.
Extending a class is similar to implementing an
interface.
–
Key Difference:
●
–
A superclass provides functionality, while an interface
makes promises.
A class can implement many interfaces, but it can
only have one superclass.
Extending a Class
Extending a Class
Extending a Class
●
Polymorphism and Inheritance
–
Light class could be extended by a ColoredLight
class which also has a char indicating its color.
–
The color is determined randomly in the
constructor.
●
Red, green, or blue ColoredLights
Extending a Class
Extending a Class
Extending a Class
●
Although ColoredLight inherits the field on, it
does not have direct access to the field.
–
Must work through the inherited method isOn()
because the field on is private in Light.
–
Private means that no other class, not even a
subclass of Light, has direct access to on.
Extending a Class
Extending a Class
●
A variable of type Light can hold an instance
of Light or of any subclass of Light.
–
●
●
●
Light bulb = new ColoredLight();
All of the methods defined in the Light class
are available to ColoredLight.
Every method in Light has to be either
inherited or overridden.
It is safe to call such a method on bulb.
–
bulb.setOn(false);
Extending a Class
●
●
If we invoke toString() on bulb, Java uses the
class of the instance (ColoredLight) instead of
the type of the variable (Light) to determine
which version of the method to use.
Dynamic dispatch
–
●
The decision is made dynamically at run time rather
than once and for all at compile time.
Chains of inheritance
–
Can we make a subclass of subclass? Sure!
Extending a Class
Extending a Class
Extending a Class ($)
●
Proper descendants
–
●
Descendants
–
●
Light itself plus its proper descendants.
Proper ancestors
–
●
ColoredLight and FlashingColoredLight
Light and ColoredLight are proper ancestors of
FlashingColoredLight.
Ancestors
–
All three classes are ancestors of
FlashingColoredLight.
Extending a Class
●
●
ColoredLight and FlashingColoredLight are
both sublasses of Light, but only
ColoredLIght is a direct subclass.
Light and ColoredLight are superclasses of
FlashingColoredLight, but ColoredLight is
the direct superclass.
Extending a Class
●
●
●
●
●
●
If an instance of the new class is just like an instance
of the old class, with only a few modifications, we
should extend it.
For example, a ColorLight is a Light, but with the
added feature of color, so extension is appropriate.
If an instance of the new class merely has an instance
of the old class as a component, we should not extend
it.
For example, an instance of BeetleGame merely has
two beetles, so it is not appropriate for it to extend
Beetle.
These are is-a (yes) and has-a (no) relationships.
Refer to
http://www.tutorialspoint.com/java/java_inheritance.htm
Extending a Class
Extending a Class
Extending a Class
●
●
Output of the LightString class looks like:
Inheritance should be used only when an
instance of the subclass can stand in for an
instance of the superclass.
–
Example
●
●
A class Bicycle with a method pedal().
Motorcycle should not extend Bicycle, because the
pedal() method wouldn't make sense for a Motorcycle.
Extending a Class
The Object Class ($)
●
●
●
Object can hold a reference to any object.
The Object class is an ancestor to every other
class.
If a class doesn't say that it extends some other
class, means it extends from Object.
The Object Class
●
●
●
●
The Object class does have a few methods that
are usually overridden.
The equals() method for the Object class
behaves exactly like ==.
In order to override the equals(), a method must
be provided with the same signature.
If we use a different argument type, we are not
overriding the method, but merely overloading
the name with a method accepting a different
argument type.
The Object Class
●
The toString() method for the Object class
returns a String like:
–
java.lang.Object@9c26f5
●
●
The Instance location in memory is 9c26f5
The instance type (class of instance) is java.lang.Object
The Object Class
●
Implicit Constructors
–
Every class that does not provide an explicit
constructor gets an implicit zero-argument
constructor which does nothing but invoke the
zero-argument super constructor.
–
E.g. super(); (line 9 in Fig. 3-4, p71) Java
allows us to omit this line.
Packages and Access Levels
●
●
●
A method encapsulates an algorithm.
A class encapsulates state (fields) and behavior
(methods).
A package which contains a number of classes
provides encapsulation on an even larger scale.
–
Classes divided into packages helps keep the
classes organized.
–
It gives programmers more freedom in choosing
names.
Packages and Access Levels
●
●
There are over 100 packages with Java
software.
Some commonly used:
Packages and Access Levels
●
The full name of a class includes both its
package name and its class name.
–
Example:
●
Object is java.lang.Object
–
Within a package, the package name can be
dropped.
–
Java doesn't require us to explicitly name the
java.lang package because the classes in this
package are used so often.
–
If there is no package declared for a class it
belongs to the default package.
Packages and Access Levels
●
To use the Scanner class from the java.util
package
–
●
import java.util.Scanner;
If we want to use several classes from a
package, it is easier to import the entire
package.
–
Example: import java.util.*;
Packages and Access Levels
●
To put a class in a particular package:
–
Before any import statements add a line at the
top of the file defining the package.
●
–
Example: package fruit;
The package structure must be reflected in the
directory structure where the files are stopped.
●
●
Package names with dots in them correspond to
nested directories.
Example: Classes in the social.relationships package
must be in the relationships subdirectory of the social
subdirectory (social/relationships).
Packages and Access Levels
●
Access Levels
–
We have seen two access levels so far
●
Private
–
●
Public
–
–
Visible everywhere.
Protected
●
●
Visible only within the class where it is declared.
It is visible to any class which either is in the same
package or in a descendant.
If no access level is specified, a field or method
gets the default package level, which makes it
visible to all classes in the same package.
Packages and Access Levels
Fig. 3-16: The fruit package contains the classes Date and Strawberry.
The dessert package contains the classes IceCream and
ChocolateCoverdStrawberry (a subclass of Strawberry).
Packages and Access Levels
• getSeed() within Strawberry.
– If it is private, it can be accessed only within the Strawberry
class.
– If no protection level is specified, it gets the default package
level of protection, so it can be accessed only from Date and
Strawberry.
– If it is protected, it can be accessed from Date, Strawberry,
and ChocolateCoveredStrawberry.
– If it is public, it can be accessed by all classes.
• See Figure 3-15 on page 81 for details.
Level
private
(package)
protected
public
Visible to
same class only
same package only
same package and
descendents
all classes
Summary
●
●
●
●
●
Every class (except for the Object class itself)
extends one other class.
Every class is a polymorphic type
Java distinguishes between the type of a variable
and the class of the instance to which it refers.
A subclass inherits the methods and fields of its
superclass, but it can override methods in the
superclass and add new fields and methods.
Classes can be grouped into packages.
Chapter 3 Self-Study Homework
●
Pages: 76-84
●
Do the following problems: 3.3, 3.4
●
Note: If necessary, hand in the error-free
program and screenshot of the execution
results for each exercise.