unit12PowerPointX

Report
Object-Oriented Programming
(Java), Unit 12
Kirk Scott
1
Inheritance, Part I
• 12.1 What is Inheritance?
• 12.2 Writing the Code for Subclasses
• 12.3 Access to Instance Variables and
Overriding Methods
2
• 12.4 A Note on the Meaning of
Inheritance
• 12.5 The Key Word super, Methods,
and Construction
• 12.6 References to Classes and
Subclasses in Programs and Methods
3
12.1 What is Inheritance?
4
12.1.1 Superclass/Subclass, Parent
Class/Child Class Terminology
• The class at the top of an inheritance
hierarchy has nothing above it.
• Any other class has exactly one class
immediately above it in the hierarchy.
• Any given class may have more than one
class above it, at different levels in the
hierarchy.
5
• The class immediately above a given class
may be called the parent class or
superclass.
• All classes above it are known generally
as superclasses.
6
• A class can have more than one class
immediately below it.
• Below that may be others, and so on.
• A class immediately below a given class
may be called a child class or a subclass.
• All classes below it are known generally as
subclasses.
7
12.1.2 "Is-a" or "Is-a-Kind-of"
Relationships
• The relationship between items in an
inheritance hierarchy can be described as
an “is a” or “is a kind of” relationship.
• Any class that appears lower down in the
hierarchy must be an example of, or a
more specific kind of, whatever classes
appear above it in the hierarchy.
8
• In the field of biology the classification of
all living things is based on this idea.
• This is referred to as taxonomy.
• The taxonomy of human beings is shown
on the next overhead.
• This illustrates one relatively complete
branch of an inheritance hierarchy.
9
• Kingdom: Animalia
– Phylum: Chordata
• Class: Mammalia
– Order: Primates
» Family: Hominidae
»
»
Genus: Homo
Species: sapiens
10
12.1.3 Inheritance Hierarchies are TreeLike
• The UML-like diagram on the next
overhead illustrates the tree-like nature of
inheritance hierarchies.
• This is described as a tree, although it is
customary to represent it “upside down”,
with the root at the top.
11
Animalia
Chordata
Mammalia
Aves
Arthropoda
Reptilia
Insecta
Arachnida
12
12.1.4 In Java the Root Class and the
Default Parent Class is Named Object
• In Java the single class at the top of the
hierarchy, or the root of the tree, is a class
named Object.
• All system supplied classes are arranged
in a hierarchy beneath this class.
• When a programmer writes classes and a
parent class is not specified, such classes
become children, or immediate
subclasses, of the Object class.
13
• There is a syntax allowing programmers to
specifically make one class a subclass of
another.
• It will be covered later.
14
12.1.5 Subclasses Inherit Instance Variables
and Methods, but Not Constructors
• Classes in the hierarchy are related by
inheritance.
• Any class that has classes above it in the
hierarchy inherits characteristics of those
superclasses.
• These characteristics include instance
variables and methods.
• Constructors are not inherited.
15
• It is natural, and possible, for subclasses to add
instance variables and methods which do not
exist in the superclasses.
• This is the main way in which subclasses
distinguish themselves from their superclasses.
• There may also be situations where it is
undesirable to inherit characteristics.
• There is syntax which thwarts inheritance.
• It will be covered later.
16
12.1.6 Do Not Confuse Individual
Inheritance with Class Inheritance
• Different uses of the term inheritance can
potentially lead to confusion.
• Inheritance can be used to refer to the
characteristics an individual child receives
from a particular parent, for example.
• This is not the sense of inheritance as it's
used here.
17
• The taxonomic example shows inheritance
among categories, not individuals.
• This does illustrate the sense of
inheritance as it's used here.
• For example, the genus Homo is the
parent class of the species sapiens in the
hierarchy.
• Homo doesn't represent some individual
parent and sapiens doesn't represent
some individual child.
18
12.1.7 The Hierarchy Containing Rectangle2D
in the Java API Documentation
• The Java API documentation for the class
Rectangle2D shows an inheritance hierarchy.
java.lang.Object
java.awt.geom.RectangularShape
java.awt.geom.Rectangle2D
• Object is the parent class of RectangularShape
and RectangularShape is the parent class of
Rectangle2D.
19
• The class names are fully qualified using
dot notation to show which packages they
are in, java.lang or java.awt.geom.
• Package membership does not indicate
inheritance relationships.
20
12.2 Writing the Code for
Subclasses
21
12.2.1 The Food Class Example
• Consider a class, FoodV1, which represents
kinds of food items from the point of view of the
store where they are sold.
• Code for this class is given on the next
overhead.
• The instance variables for this class are name,
wholesaleCost, and markup.
• By default, this class is a subclass of the Object
class.
22
• public class FoodV1
• {
•
private String name;
•
private double wholesaleCost;
•
private double markup;
•
public FoodV1()
•
{
•
}
•
public void setName(String nameIn)
•
{
•
name = nameIn;
•
}
•
public String getName()
•
{
•
return name;
•
}
23
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
• }
public void setWholesaleCost(double wholesaleCostIn)
{
wholesaleCost = wholesaleCostIn;
}
public double getWholesaleCost()
{
return wholesaleCost;
}
public void setMarkup(double markupIn)
{
markup = markupIn;
}
public double getMarkup()
{
return markup;
}
public double getPrice()
{
return (wholesaleCost + wholesaleCost * markup);
}
24
12.2.2 Creating Subclasses
• It is possible to create a class,
TaxedFoodV1, which is a subclass of the
FoodV1 class.
• Here is a UML diagram showing the
inheritance relationship between these
classes and the Object class:
25
Object
FoodV1
TaxedFoodV1
26
12.2.3 The Keyword extends
• The keyword for specifying a subclass is
extends.
• Syntactically, the child specifies its one
parent; the parent doesn’t specify its
potentially many children.
• Here is the code for the TaxedFoodV1, a
child class of FoodV1:
27
• public class TaxedFoodV1 extends FoodV1
• {
•
private double taxRate;
•
public TaxedFoodV1()
•
{
•
}
•
public void setTaxRate(double taxRateIn)
•
{
•
taxRate = taxRateIn;
•
}
•
public double getTaxRate()
•
{
•
return taxRate;
•
}
• }
28
12.2.4 Constructors
• There is nothing unusual about the
TaxedFoodV1 class regarding
construction
• It has a default constructor and an
instance of the class can be constructed
as usual:
• TaxedFoodV1 myTaxedFood = new
TaxedFoodV1();
29
12.2.5 The Inheritance of Instance
Variables
• The TaxedFoodV1 class has one instance
variable of its own, taxRate.
• The class also inherits all of the instance
variables of the class FoodV1.
• An object of this class (e.g., myTaxedFood) has
all of the following instance variables:
• name
inherited
• wholesaleCost
inherited
• markup
inherited
• taxRate
not inherited
30
12.2.6 The Inheritance of Methods
• The TaxedFoodV1 class has get and set
methods for the instance variable taxRate
defined in it.
• It also inherits all of the methods (which were
declared public) of the class FoodV1.
• After an instance of myTaxedFoodV1 has been
constructed, calls to the inherited methods can
be freely made on it.
31
• TaxedFoodV1 myTaxedFood = new
TaxedFoodV1();
• myTaxedFood.setname(“Peas”);
• double retrievedCost =
myTaxedFood.getWholesaleCost();
• double retrievedPrice =
myTaxedFood.getPrice();
32
12.3 Access to Instance Variables and
Overriding Methods
33
12.3.1 Inherited Instance Variables Are
Not Directly Accessible
• Both (private) instance variables and (public)
methods are inherited.
• Inherited instance variables declared private in
the superclass (as they should be) are not
directly accessible in the subclass.
• When using an instance of a subclass, it is
possible to work with the object’s inherited
instance variables by using the inherited get and
set methods.
34
12.3.2 Thwarting Inheritance by
Overriding Methods
• As subclasses become more specific, it is
possible that an inherited method does not
completely accomplish what needs to be
accomplished.
• It is syntactically possible for a subclass to
have a method with the same name as a
method in one of its superclasses, and
with the same parameter list.
35
• This is referred to as overriding the
inherited method.
• If a call is made on an object of the
subclass using that method name, the
version of the method defined in the
subclass is used, not the version in the
superclass.
• Inheritance is thwarted by overriding.
36
12.3.3 Do Not Confuse Overriding with
Overloading
• It is also possible to write a method in a
subclass with the same name as a method
in one of its superclasses, but with a
different parameter list.
• In this case you have not overridden the
inherited method.
• This is overloading.
• The two should not be confused.
37
• Overloading also applies in the simpler case of a
single class
• A given class may have two methods with the
same name but different parameter lists
• The system distinguishes between them based
on the parameter list
• Having the same name, the two methods should
accomplish approximately the same thing, but
on the basis of different input parameters
38
12.3.4 An Example Illustrating Overriding
• The method getPrice() as defined in the
class FoodV1 calculates a checkout price
based on the wholesale cost of the item
and the markup charged by the store.
• The checkout price for a taxed food item
should include the tax on that item.
• This shows how the method might be
correctly implemented in the
TaxedFoodV1 class:
39
• public double getPrice()
• {
•
double retrievedCost;
•
double retrievedMarkup;
•
double costPlusMarkup;
•
double price;
•
retrievedCost = getWholesaleCost();
•
retrievedMarkup = getMarkup();
•
costPlusMarkup = retrievedCost +
retrievedCost * retrievedMarkup;
•
price = costPlusMarkup + costPlusMarkup
* taxRate;
•
return price;
• }
40
12.3.5 Lack of Direct Access
• There is no direct access to the inherited
instance variables.
• The code above has to use the get
methods to access the inherited variables.
• retrievedCost =
getWholesaleCost();
• retrievedMarkup = getMarkup();
41
12.3.6 Remembering the Implicit
Parameter
• The code given on the previous overhead
illustrated method calls “hanging in space”
• The standard way of calling a method is
object.method()
• In the code above, the method calls were
not made on objects
• That means that the calls were being
made on the implicit parameter
42
• The calls could be written using the implicit
parameter.
• retrievedCost =
this.getWholesaleCost();
• retrievedMarkup =
this.getMarkup();
• The retrieved values come from whatever
object the getPrice() method, which
contains these calls, was called on.
43
12.3.7 Review of Lack of Direct Access
and Overriding
• This example illustrated implementing a
version of the getPrice() method in a
subclass which differs from the
implementation that it would otherwise
inherit.
• This is overriding.
• When calling the overridden method on a
subclass object, the implicit parameter of
the call to getPrice(), would be a
TaxedFoodV1 object
44
• The TaxedFood object would have
wholesaleCost and markup variables by
inheritance.
• However, in the subclass code for the
getPrice() method, there would not be
direct access to these inherited variables.
• The inherited variables can only be
accessed through inherited get methods—
whether done with calls “hanging in space”
or calls on the implicit parameter, “this”.
45
12.3.8 Using the Overridden
Method
• Suppose that the following objects were
constructed:
• FoodV1 myFood = new FoodV1();
• TaxedFoodV1 yourFood = new
TaxedFoodV1();
• Suppose also that set methods had been
called so that their price, markup, and
taxRate variables had been set.
46
• Now consider the following two calls:
• double x = myFood.getPrice();
• double y = yourFood.getPrice();
47
• The two calls to getPrice() in the lines of
code above are to two different versions of
the method.
• Which version of the method is called
depends on which kind of object it is called
on, an instance of FoodV1 or an instance
of TaxedFoodV1.
48
12.3.9 Inheritance from Multiple Levels
• Consider the following general inheritance
hierarchy:
Top
Middle
Bottom
49
• If methodX() is implemented in the Top
class and not implemented in the other
two classes, then it is inherited by both
Middle and Bottom.
• If methodX() is implemented in Middle,
then it does not exist for objects of the Top
class; it is inherited by the Bottom class.
50
• If methodX() is implemented in the Top
class, overridden in the Middle class, and
inherited by the Bottom class, the version
nearest to the Bottom class as you move
upwards through the hierarchy is inherited;
this is the version implemented in the
Middle class.
51
12.3.10 Instance Variables Can't Be
Overridden
• It is not possible to override instance variables.
• It is syntactically possible to declare instance
variables in a subclass with the same name as
instance variables in its superclasses (and with
different types).
• It is unfortunate that this is syntactically possible,
because from a practical point of view it is a big
mistake to do something like this.
• It will be extremely difficult to unravel the
meaning of the code.
52
• The idea of overriding instance variables is
also a problem conceptually.
• Instance variables should represent
inherent characteristics of classes.
• If it seems desirable to change an instance
variable in a subclass, that’s a sign that
that class is in the wrong place in the
inheritance hierarchy.
53
12.4 The Meaning of Inheritance: Some
Differences with the Sun Java Tutorial
Presentation
• If you haven’t looked at the Java Tutorial,
then there is no need to consider this
section in the note files.
• With the exception of this overhead, it will
not be covered in class in any case.
• If you have questions about it you should
read the section in the note file (and ask
questions if you have them).
54
12.5 The Key Word super, Methods, and
Construction
55
12.5.1 Using super to Call an Overridden
Method
• In the overridden getPrice() method of the
TaxedFoodV1 class, the majority of the
code simply duplicated the logic of the
getPrice() method of the FoodV1 class.
• It was necessary to get the price including
the markup and then apply the tax rate to
that.
56
• Finding the price with the markup is
exactly what the getPrice() method does
in the superclass.
• The example below shows how it is
possible for the overridden method to
make use of the version of the method
defined above it in the hierarchy.
57
• public double getPrice()
•{
•
double price;
•
price = super.getPrice();
•
price = price + price * taxRate;
•
return price;
•}
58
• At execution time the key word super signals
that the call to getPrice() is not a recursive call.
• The system looks in the hierarchy for the nearest
class above the current class where getPrice()
is implemented, and uses the version found
there.
• The keyword super does not signify an object
• The method is called on the implicit parameter
59
12.5.2 Subclass Constructors Don't Have
Access to Inherited Instance Variables
• The keyword super also arises when writing
subclass constructors which take parameters.
• Constructors in a subclass also do not have
direct access to the (private) instance variables
inherited from the superclass.
• For example, super is needed in order to write a
constructor for the TaxedFoodV1 class which
would take parameters for the inherited instance
variables wholesaleCost and markup.
• This will be illustrated shortly
60
12.5.3 If the Programmer Writes a Constructor,
the System Doesn't Supply a Default
Constructor
• It is possible to write a class with no constructors
at all.
• If this is done, the system automatically provides
an invisible default constructor.
• It is important to remember that as soon as the
programmer writes any constructor for a class,
then the system does not provide a default
constructor.
• In this case, if a default constructor is needed,
the programmer has to provide one.
61
12.5.4 Using super When Writing a
Subclass Constructor with Parameters
• The example so far has made use of default
construction.
• Default subclass construction relies on the
existence of a default constructor in the
superclass.
• Default initialization of instance variables,
including inherited ones, is handled
automatically.
• The example will now be extended to illustrate
construction with parameters.
62
• Here is a constructor for the superclass,
FoodV2, which takes a full set of parameters for
its instance variables:
• public FoodV2(String nameIn, double
wholesaleCostIn, double markupIn)
•{
•
name = nameIn;
•
wholesaleCost = wholesaleCostIn;
•
markup = markupIn;
•}
63
• Here is a correct constructor for the subclass,
TaxedFoodV2, which takes a full set of
parameters, including parameters for the
inherited variables:
• public TaxedFoodV2(String nameIn,
double wholesaleCostIn, double
markupIn, double taxRateIn)
•{
•
super(nameIn, wholesaleCostIn,
markupIn);
•
taxRate = taxRateIn;
•}
64
12.5.5 If You Use super, It has to be First; If You Don’t
Use super, there has to be a Default Superclass
Constructor
• When the system encounters a call to super() in
a constructor, it looks for a constructor above the
current class in the hierarchy.
• It will use the nearest constructor in the
hierarchy above it which has a parameter list
which matches the parameters used in the
super() call.
• If you explicitly call super() in a subclass
constructor, this call has to be the first line of
code.
65
• If you don’t explicitly call super(), then you are
relying on the default constructor in the
superclass.
• Construction depends on cascading calls to
constructors up through the inheritance
hierarchy, whether the calls are explicit calls to
super() or whether they are implicit calls which
rely on the existence of a default constructor in
the superclass.
66
• The actual creation of a new object
ultimately stems from a call to the
constructor in the Object class.
• The constructors below that class are
responsible for initializing the instance
variables.
67
12.6 References to Classes and
Subclasses in Programs and Methods
68
12.6.1 Class Hierarchies Have to Be
Written from the Top Down
• When creating a hierarchy of classes, you have
to work your way from the top down.
• The code for a subclass can only be compiled if
its superclasses exist.
• The code for superclasses should also be tested
before the subclass code is written.
• A test program at any level includes code that
makes use of all constructors and methods in
the class to make sure that they work correctly.
69
Note on programming
assignments
• The previous bullet bears repeating:
• Some of the programming assignments
specify that certain classes be written and
that test programs for those classes also
be written.
• This is what is meant by a test program:
• Code that makes use of all constructors
and methods in the class to make sure
that they work correctly.
70
12.6.2 Superclass References to Subclass Objects are
Valid. This is Done without Casting
• Syntactically, a reference to a subclass
object can always be assigned to a
reference that is declared to be of the type
of any of the subclass’s superclasses.
• This is logically valid because instances of
classes lower down in the hierarchy are “a
kind of” (a more specific kind of) the
classes higher in the hierarchy.
71
• Syntactically, this idea can be illustrated
as follows:
• FoodV2 myFood;
• TaxedFoodV2 myTaxedFood = new
TaxedFoodV2(“bread”, .50, .05,
.07);
• myFood = myTaxedFood;
72
12.6.3 Superclass References to Subclass Objects
Don't Have Access to Methods Defined Only in the
Subclass
• A superclass reference to a subclass object is
distinctly limited, or has a distinct limitation.
• When working with a superclass reference, it is
only possible to call methods defined in the
superclass or methods inherited by the
superclass.
• It is not possible to call methods on a superclass
reference if the methods are only defined in the
subclass.
73
12.6.4 It is Possible to Recover a
Subclass Reference by Casting
• Casting can be used in order to recover
the actual class that a superclass
reference belongs to.
• The previous code example is repeated on
the next overhead with one line added.
• In the final line the TaxedFoodV2
reference is recovered from the FoodV2
reference:
74
•
•
•
•
•
FoodV2 myFood;
TaxedFoodV2 myTaxedFood =
new TaxedFoodV2(“bread”, .50, .05, .07);
myFood = myTaxedFood;
TaxedFoodV2 newTaxedFood = (TaxedFoodV2) myFood;
75
12.6.5 Subclass References to
Superclass Objects Are Not Valid
• Casting will not work if the type on the left is not
the same type as the actual object on the right.
• Here is a gross example:
• /* NO! NO! NO! */
• Ellipse2D.Double myEllipse = new
•
Ellipse2D.Double(10, 20, 30, 40);
• TaxedFoodV2 myTaxedFood =
•
(TaxedFoodV2) myEllipse;
76
• This looks more plausible but is equally
impossible:
• /* NO! NO! NO! */
• FoodV2 myFood = new
•
FoodV2(“cheese”, 1.25, .06);
• TaxedFoodV2 myTaxedFood =
•
(TaxedFoodV2) myFood;
77
• Even though myFood and myTaxedFood
are in the same inheritance hierarchy,
myFood is a superclass object (only).
• It never was a taxed food, and a reference
to a taxed food object cannot be
recovered.
78
• In general it is not valid to try and cast
superclasses to subclasses because a
superclass is not “a kind of” a subclass.
• Casting can recover the actual subclass of
a superclass reference.
• It cannot recover a kind of reference that
never existed.
79
• Referring back to the taxonomic example, there
is no problem with referring to a human being as
an member of the class Animalia
• All humans are animals
• However, casting an Animalia reference to a
human is problematic.
• What if the Animalia reference were a
superclass reference to an instance of a spider?
80
12.6.6 The Keyword instanceof Checks
Whether an Object is an Instance of a Given
Class
• The keyword instanceof functions as an
operator that returns a boolean value.
• It compares the actual type of a reference to a
given class.
• This code fragment shows its use to permit a
valid cast and prevent a mistaken one:
• if(myFood instanceof TaxedFoodV2)
• TaxedFoodV2 newTaxedFood =
(TaxedFoodV2) myFood;
81
12.6.7 The Actual Parameter in a Method Call Can Be a
Subclass of the Formal Parameter Type. Automatic
Conversion to a Superclass Reference Occurs
• Reference type becomes critical when
passing object references as parameters.
• A subclass object can always be assigned
to a superclass reference.
• If a formal parameter is typed as a
superclass reference in a method, it is
permissible to pass a subclass object or
reference as the actual, explicit parameter
when calling the method.
82
• A new method,
setMarkupToThisMarkup(), is given on
the next overhead.
• This method is defined in the FoodV3
class.
• The method is designed to set the markup
of one food item to the markup already
stored in another.
• This is accomplished by passing the other
object as a parameter to the method.
83
• The parameter is typed FoodV3, the same as
the class the method is defined in.
• public void
setMarkupToThisMarkup(FoodV3
anotherFood)
•{
•
double tempMarkup =
anotherFood.getMarkup();
•
setMarkup(tempMarkup);
•}
84
• Suppose the following code exists in a program that uses the food
classes:
• TaxedFoodV3 myTaxedFood =
•
new TaxedFoodV3(“bread”, .50, .05, .07);
• TaxedFoodV3 yourTaxedFood =
•
new TaxedFoodV3(“milk”, .75, .08, .07);
• myTaxedFood.setMarkupToThisMarkup(yourTaxedFood);
85
• The third (last) line of code is the critical
one.
• The new method is inherited by the
TaxedFoodV3 subclass, making the call
on myTaxedFood is possible.
• The actual, explicit parameter,
yourTaxedFood, is an instance of
TaxedFoodV3.
• In the method definition the formal
parameter is typed FoodV3.
86
• In other situations where the actual
parameter type did not agree with the
formal parameter type, the compiler
detected an error.
• However, in this case there is no problem.
• When passing a parameter, the actual
parameter is assigned to the formal
parameter.
• It is OK to assign a subclass object to a
superclass reference without casting.
87
• The system knows that TaxedFoodV3 is a
subclass of FoodV3.
• Therefore, when the actual parameter, a
taxed food object, is passed, that
reference is automatically converted to a
FoodV3 superclass reference.
88
12.6.8 In the Body of a Method Definition, Method Calls
Can Be Made on a Formal Parameter Which Is a
Superclass Reference
• This line of code appears in the body of the
method:
• double tempMarkup =
anotherFood.getMarkup();
• If the actual parameter is a subclass object, then
anotherFood is a superclass reference.
• A superclass reference is distinctly limited.
• It is only possible to call methods defined in the
superclass on such a reference.
• This does not raise a problem.
89
• The method getMarkup() is written in the
FoodV3 (super) class.
• Therefore it's possible to call it on a superclass
reference to a subclass object.
• The TaxedFoodV3 class inherits this method.
• The version defined in the superclass is
appropriate for the actual subclass object it’s
called on.
• If the method being called were overridden, that
would still be OK.
• How that works will be described in a later
section.
90
• To summarize, the point of the example is
that it is possible to pass a subclass object
as an explicit parameter when the formal
parameter is typed to a superclass.
91
• It is also worth noting that the code for the
method could be simplified.
• It is true that a superclass reference is
distinctly limited and doesn’t have access
to methods defined only in a subclass.
• It’s also true that a subclass object doesn’t
have direct access to its inherited instance
variables.
92
• However, if you are writing code in the
superclass, a superclass reference (to a
subclass object) will have access to those
variables (inherited by the subclass) which are
defined in the superclass.
• In other words, the simpler version of the
setMarkupToThisMarkup() method given on
the next overhead will work, both if the
parameter is a Food object or a TaxedFood
object.
93
• public void
setMarkupToThisMarkup(FoodV3
anotherFood)
•{
•
markup = anotherFood.markup;
•}
• /* Or:
•
this.markup = anotherFood.markup;
• */
94
12.6.9 Example Code (Showing All
Changes up to this Point)
• public class FoodV3
• {
•
private String name;
•
private double wholesaleCost;
•
private double markup;
•
public FoodV3(String nameIn, double wholesaleCostIn,
double markupIn)
•
{
•
name = nameIn;
•
wholesaleCost = wholesaleCostIn;
•
markup = markupIn;
•
}
95
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
public void setName(String nameIn)
{
name = nameIn;
}
public String getName()
{
return name;
}
public void setWholesaleCost(double wholesaleCostIn)
{
wholesaleCost = wholesaleCostIn;
}
public double getWholesaleCost()
{
return wholesaleCost;
}
96
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
public void setMarkup(double markupIn)
{
markup = markupIn;
}
public double getMarkup()
{
return markup;
}
public double getPrice()
{
return (wholesaleCost + wholesaleCost *
markup);
}
public void setMarkupToThisMarkup(FoodV3
anotherFood)
{
double tempMarkup = anotherFood.getMarkup();
setMarkup(tempMarkup);
}
}
97
• public class TaxedFoodV3 extends FoodV3
• {
•
private double taxRate;
•
public TaxedFoodV3(String nameIn, double
wholesaleCostIn, double markupIn, double
taxRateIn)
•
{
•
super(nameIn, wholesaleCostIn,
markupIn);
•
taxRate = taxRateIn;
•
}
•
public void setTaxRate(double taxRateIn)
•
{
•
taxRate = taxRateIn;
•
}
98
•
•
•
•
•
•
•
•
•
•
•
• }
public double getTaxRate()
{
return taxRate;
}
public double getPrice()
{
double price;
price = super.getPrice();
price = price + price * taxRate;
return price;
}
99
What is the First Assignment
Like?
• The contents of the first assignment are
presented on the following overheads.
• When doing the assignment, you should
work from the Word document, not these
overheads.
• The assignment is given here so that it will
be possible to go over it in class if there’s
time after finishing the lecture.
100
Java Unit 12 Assignment
• Grading check-off checklist:
• 1. I will want to see that answers have
been typed in for the 19 short answer
questions.
• 2. You should have an ItemB.java class
which compiles.
101
• 3. You should have FoodV4.java,
PackagedFoodV4.java, and BulkFoodV4.java
classes which compile.
• 4. You should have a test program (.java file) for
the three classes above which compiles and
runs.
• When you prepare to demonstrate this, recall
that if you used MyTerminalIO.java, it should
also be in the folder so that your program will
compile and run.
102
Assignment:
• 1. Describe in words what the class named Object is in
Java.
• 2. What class in Java is at the very top of the
inheritance hierarchy?
• 3. Do subclasses get copies of the instance variables
that are declared private in their superclasses?
• 4. Do subclasses have free access to their inherited
private instance variables?
• 5. Can the type of private (or public) instance variables
be overridden in a subclass?
103
• 6. Only one of the following statements is true. Which is
it?
• A. Constructors are inherited.
• B. Constructors in subclasses rely on the existence of
constructors in superclasses, but the constructors are
not literally inherited.
• 7. Are public methods inherited?
• 8. Do subclasses have free access to their inherited
public methods?
• 9. Can the implementation of an inherited method be
overridden in a subclass?
104
• 10. Suppose an inheritance hierarchy consists of classes
named Top, Middle, and Bottom, in that relation.
• Suppose methodX() is defined in Bottom, but not above it.
• Can this method be called on objects of the Middle class?
• 11. Suppose an inheritance hierarchy consists of classes
named Top, Middle, and Bottom, in that relation.
• Suppose methodX() is defined in Top, overridden in Middle,
and is not overridden in Bottom.
• What happens if methodX() is called on an object of the
Bottom class?
105
• 12. Suppose an inheritance hierarchy consists of
classes named Top, Middle, and Bottom, in that
relation.
• Suppose methodX() is defined in Top and overridden in
Bottom.
• What does the use of the key word super accomplish
when used in the version of the method in Bottom?
• 13. Suppose the key word super is used in a subclass
constructor definition.
• If so, where does it have to appear?
106
• Two sketchy class definitions are shown
on the next overheads.
• Assume that everything exists to make
these classes work in reality.
107
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
public class ParentClass
{
public double method1(double inVal)
{
…
}
public double method2(double inVal)
{
…
}
public static double method3(ParentClass pClassRef, double inVal)
{
…
double someResult = pClassRef.method2(inVal);
…
}
…
}
108
•
•
•
•
•
•
•
•
•
•
•
•
•
public class ChildClass extends ParentClass
{
public double method2(double inVal)
{
…
}
public double method4(double inVal)
{
…
}
…
}
109
• Also suppose that the following declarations and
constructions are done:
•
• ParentClass myparent = new ParentClass();
• ParentClass yourparent = new
ParentClass();
• ParentClass parentClassRef;
• ChildClass mychild = new ChildClass();
• ChildClass childClassRef;
110
• 14. Suppose that in the implementation of the
version of method2() that occurs in the
ChildClass it is necessary to call the version of
method2() that occurs in the ParentClass.
• If the parameter being passed is inVal, what
would the call look like?
• 15. Is this sequence OK?
• parentClassRef = mychild;
• double result =
parentClassRef.method4(someVal);
111
• 16. In what class is the version of method1()
defined that is being used in the call?
• double result =
mychild.method1(someVal);
• 17. In what class is the version of method2()
defined that is being used in the call?
• double result =
mychild.method2(someVal);
112
• 18. In what class is the version of
method2() defined that is being used
when the code for method3() is run?
• (This question refers to the call to
method2() which is made in the body of
method3().)
• double result =
yourparent.method3(myparent, someVal);
113
• 19. In what class is the version of
method2() defined that is being used
when the code for method3() is run?
• (This question refers to the call to
method2() which is made in the body of
method3().)
• double result =
yourparent.method3(mychild, someVal);
114
• The complete code for a simple class is
given on the next overhead.
115
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
public class ItemA
{
private double price;
public ItemA()
{
}
public ItemA(double priceIn)
{
price = priceIn;
}
public void setPrice(double priceIn)
{
price = priceIn;
}
public double getPrice()
{
return price;
}
}
116
• The following questions together form the
definition of a subclass of the given class.
• They are given here as separate questions to
illustrate how questions might be presented on a
test.
• For the purposes of the assignment, write the
code for ItemB and save it as a .java file, along
with ItemA.java, so that it can be checked off by
a successful compilation.
117
• 20. Give the line of code which would declare
ItemB as a subclass of ItemA.
• 21. Give the line of code which would give
ItemB an int instance variable named units.
• (The assumption is that whatever unit you’re
using, you record the nearest whole value.)
• 22. Write a set method, setUnits() with input
parameter unitsIn.
118
• 23. Write a get method, getUnits().
• 24. Write a default constructor for ItemB.
• 25. Give a complete constructor for ItemB
which would take input parameters priceIn
and unitsIn and successfully use them to
initialize the instance variables.
• 26. Write a method getUnitPrice() that
will return the result of dividing price by
units.
119
• A new food hierarchy is described below.
• Your task is to write the code for all of the classes described and
write a program that tests all of the constructors and methods
contained in each of the classes.
• Because of the changes required, the food class will become
version 4.
• In order to keep the naming of the subclasses consistent, they will
also be named version 4.
• The idea is again to represent food items from the point of view of
the store where they are sold.
• Packaged food comes in cans or boxes that contain a specific
amount. Bulk food is measured at the time of sale.
• A UML diagram is shown on the next overhead.
120
FoodV4
PackagedFoodV4
BulkFoodV4
121
• 27. The class FoodV4 should contain the
following:
• Instance variables: String brand, String
productName
• Methods: get and set methods for both instance
variables, plus a method
setBrandToThisBrand(Food
anotherFoodItem)
• Constructors: one constructor that takes two
parameters, one for each instance variable
122
• The setBrandToThisBrand() method should be
similar to the setMarkupToThisMarkup()
method in the examples in the chapter.
• It is designed to illustrate passing an object
reference as a parameter.
• The implicit parameter should receive a new
value for its brand instance variable, the value
currently in the explicit parameter.
123
• 28. The class PackagedFoodV4 should
contain the following:
• Instance variables: String units, double
size, double itemCost
• Methods: get and set methods for the
instance variables, plus a method named
getUnitCost()
• Constructors: one constructor that takes 5
parameters, one for each instance variable
124
• The instance variable units refers to the
units in which the product is measured,
such as grams or milliliters.
• The instance variable size tells how many
of those units are in a package.
• The method getUnitCost() calculates the
cost per unit based on the itemCost and
the size of the item.
125
• 29. The class BulkFoodV4 should contain the
following:
• Instance variables: String units, double
unitCost
• Methods: set and get methods for the instance
variables, plus a method named
findCost(double amount) which will return the
cost of a given amount of the product
• Constructors: one constructor that takes 4
parameters, one for each instance variable
126
• Notice that in this class there will be a method
getUnitCost() which is a simple accessor method.
• It does not require calculation.
• Also, with respect to the value it returns, the method
findCost() is similar to getItemCost() in the
PackagedFood class.
• However, it is not a simple accessor.
• It is a method which takes an explicit parameter because
it is not possible to determine the cost of a bulk food item
without specifying the amount being bought or sold.
127
• 30. Test the classes.
• This may be done with one big program, or with separate
programs for the different classes.
• The test program should create instances of the objects,
testing each of the constructors you have written, and it
should also test each of the methods in each of the classes in
order to make sure that they function as they should.
• It should be a particularly interesting test to see if the
setBrandToThisBrand() method works when the implicit
parameter is a PackagedFoodV4 item and the explicit
parameter is a BulkFoodV4 item, for example, or the other
way around.
128
The End
129

similar documents