10. Example – Suppose the Dogclass provides the method shownon the right where a Dog can barkAt another Dog. Define somedogs:publicString barkAt(Dog d) {returnthis.getName() +
.
36

37

11.
Example – Consider the classes defined on the left and the static methods on the right.class A {public String toString() { return "A"; }}class B extends A {public String toString() { return "B"; }}class C extends B {}public static void m( A a ) { System.out.println( a ); } public static void m2( C c ) { System.out.println( c ); } State whether the method calls below will: (a) compile, (b) generate a run-time error, or (c) what output will itproduce?a.m( new A() );b.m( new B() );c.m( new C() );d.m2( new C() );e.m2( new B() );
38

f.
g.
Homework
h.
26.
Define these terms in your own words:i.a.Reference typeb.Supertype reference (or polymorphic reference)c.Polymorphismj.27.True or Falsek.a.You can always refer to a supertype instance with a subtype reference.b.You can always refer to a subtype instance with a supertype reference.c.You can always pass an instance of a subclass to a method with a parameter defined as a supertype.d.You can sometimes pass an instance of a superclass to a parameter defined as a subclass.
l.
m.
n.

o.
Section 11.8 – Dynamic Binding
p.
1.
Consider the example below. First, we create a WolfDog instance but give it a (supertype) Dog reference. Whenthe bark method is called, the actual barkmethod that runs is determined by the instance of the object not thereference type. Thus, the WolfDog’s bark method is called (red arrow). Next, the run method is called. Since theWolfDog class does not define a run method, the JVM finds a run method in the Dog superclass (blue arrow).Finally, the Dog reference, samis assigned to an instance of a Dogand so the Dogclass’s bark method is called(green arrow). Thus, dynamic bindingmeans that the the actual method that runs is determined at run-time bythe instance of the object, not the reference type.
q.
r.
s.
2.
The JVM goes through a process like this to implement dynamic binding
t.
u.
Get the
type
of the instance.
v.
If ( instance contains a definition for the behavior )
w.
Execute behavior
x. Else
y.
Find behavior in superclass & execute
z.
aa.
Thus, the method is
bound
to the call at run-time (
dynamically
).
ab.
3.
Non-software example – In the figure on the right,
Saxophone
,
Trumpet
, and
Trombone
are subclasses of
Horn
and each one
overrides
the
play
method in a way that is appropriate for the
specific type of instrument (instance). Thus, each plays notes

