<p>The problem is that you don't really have subtype polymorphism here. While the language permits it, it is poor practice to change the interface (set of public methods) as you move down the hierarchy. I'm not speaking of the formal <em>interface</em> but only of the messages that an object is allowed to handle. Your class Vehicle doesn't have honkHorn, but a subclass does. </p>

<p>The problem with this is that if I have an object, I need to know its specific type to know what methods it supports. Some Vehicles support honkHorn, but others don't so I need to test. </p>

<p>This is, at best, ad-hoc polymorphism. </p>

<p>If you want true subtype polymorphism define a class as an interface or abstract class as you have done here, but all subclasses should exhibit exactly the same interface. </p>

<p>Then, if you define a variable to have the interface (abstract class) type, then it can refer to any object of any subclass and it can field any message defined at the top level. You <em>never</em> need to ask instanceof and you never need to cast. </p>

<p>It is, of course, harder to build a system keeping such a pure rule, but it can be done and it saves you a ton of grief later. </p>

<p>One of the reasons we want to build OO software is to let the system figure things out without explicit testing. If you change "interfaces" within hierarchies you are just back to ad-hoc decision making. You are defeating the notion of IS-A that the OO paradigm was built for. </p>

<p>In your example you can't really say that a Bicycle IS-A Vehicle. You can say that it is a Vehicle, but something more, and we have to determine what by ad-hoc means in many instances. Sometimes by declaring variables to have a specific type (rather than a general type) and sometimes by testing. </p>

<p>In terms of "contracts", if you change the contract as you come down the hierarchy, it wasn't really a contract. </p>

<p>Sadly, too many books don't understand this and define meaningless, and difficult to work with, "hierarchies". </p>

<p>One way to avoid this issue, is to define Vehicle as an interface and then define Bicycle as another interface that extends Vehicle. Now your intent is clear. Classes implementing an interface have <em>only</em> the public methods defined in their interface and nothing more. Now you have interfaces of <em>concepts</em> which is what they are really intended to model, and classes of <em>objects</em> that conform to specific concepts. This may be the mental model you seek, actually.</p>

<hr>

<p>I discussed Polymorphism at some length here: <a href="https://cseducators.stackexchange.com/a/4050/1293">https://cseducators.stackexchange.com/a/4050/1293</a></p>

<hr>

<p>Let me add some things here to point to a better way. One of the lessons is that subclassing is generally overused. Some books present it as the "really big thing". Instead, programming by composition is much more valuable. When you create a class give it parts that are instances of some other, simpler, class. </p>

<p>For the immediate problem here. Give Vehicle a method <em>makeSound</em>. Give each subclass of it an instance field that refers to some kind of object that might make a typical sound. For a bicycle object it might be a Horn object. Then when any vehicle is sent the makeSound message it <em>delegates</em> the making of the sound to the object that is part of its composition. Delegation is the big idea here. Now you don't need to change the protocol in different classes. Just change the implementation, but giving different "parts" to different vehicles. </p>

<p>At least one very commonly used book has something like the following hierarchy. First a Point class. A point has some coordinates. Then, for the first (ugh) example of subclassing is a Circle class. This is "easy" to write, since if you subclass Point all you need to add is a radius value. But to a mathematician, is every circle a specialization of point?  It is backwards, of course. Taking it farther, a Cylinder can subclass Circle just by adding a height value. This makes it very easy to type in, but very foolish, both mathematically and from a program design standpoint. If you create a Cylinder, what sort of variable should you use to refer to it. If you don't use a Cylinder variable, then within the next few lines you are very likely to have to cast the variable, or, if you have put such things into a List then you are going to have to type case them (or equivalent) when you look at them again. Don't do that. But what <em>can</em> you do better. Use delegation. </p>

<p>When you build your Circle class, don't make it an extension of Point. Instead, give it an instance variable of type Point. A Circle is a different kind of thing. It isn't a point, but it HAS-A point as a field. </p>

<p>Likewise the Cylinder HAS-A Circle for its base. Much cleaner. The cylinder delegates some of its actions to its base when it receives a message. Likewise the base (a Circle) delegates some messages to its location (a Point).</p>

<p>Now you have a defensible design, but it might not have used subclassing at all. You get reuse (via delegation) and don't confuse the nature of things and require ad-hoc decision making throughout a long program. </p>

CC BY-SA 4.0
2018-10-13T22:19:53.980Z
This is a really interesting perspective, and something I have never heard in years of schooling. (which perhaps says something about the schooling) I always heard the oft-touted "superclasses define commonalities, subclasses define differences" model. I'm going to have to sit on this and ponder it. If I'm understanding this correctly, your perspective suggests that a non-abstract class should never extend another non-abstract class. Is this correct? Do you have any readings for me to pursue this further?
cryptic_star
CC BY-SA 4.0
2018-10-13T22:22:41.543Z
Not exactly. You can extend a class without adding to it's public interface. You can add all of the private methods you like and you can change the behavior - to (hopefully) more specific behavior. So, a Snake can _bite_. A RattleSnake can also _bite_ but it is more serious.
Buffy
CC BY-SA 4.0
2018-10-13T22:25:10.710Z
Think about whether you gain anything with your hierarchy over having Vehicle and Bicycle completely separate classes. Very little, other than typing (hitting keys), I think. And you avoid most of the traps. It isn't typing (hitting keys) that makes programming hard.
Buffy
CC BY-SA 4.0
2018-10-13T22:34:00.557Z
A horn is a decorator, as is a signal light, or an arm signal.
pojo-guy
CC BY-SA 4.0
2018-10-13T22:36:36.560Z
Well, @pojo-guy, maybe not exactly, but something like that. Use delegation, not inheritance, for such things. But yes, see the Decorator Design Pattern.
Buffy
CC BY-SA 4.0
2018-10-13T22:50:58.173Z
@Buffy Thank you both for the info. I'm going to ponder it, and I might be back here with more questions.
cryptic_star
CC BY-SA 4.0
2018-10-15T12:54:46.687Z
@Buffy A rattlesnake can also *rattle*, though.
Ben I.
CC BY-SA 4.0
2018-10-15T13:04:45.757Z
@BenI. and if you add that in a subclass then you have a bad design. You need to, then, make ad-hoc decisions about what you have - the very thing OO is designed to make unnecessary. Rethink your hierarchy. A sloppy design will pay you dividends later - in pain.
Buffy
CC BY-SA 4.0
2018-10-15T13:09:32.180Z
A remarkably bad design Point has a subclass Circle (just add a radius), which has a subclass Cylinder (just add a height). So now, every  cylinder is just a point. If you have a variable w/ type Point, what can you do with it? BTW, in at least one book, this is treated as GOOD design. If you need to know the most specific type of an object, then the hierarchy does you no good at all. It is just noise that you may as well omit. The system can no longer help you and you need it all in your head at every statement.
Buffy
CC BY-SA 4.0
2018-10-15T13:59:02.430Z
@BenI., maybe think of it this way. Is a snake that _doesn't_ rattle, a more general kind of snake or just a _different_ kind of snake? If your snake hierarchy needs warning sounds add them at the top. Now you can distinguish by behavior, not by interface.
Buffy
CC BY-SA 4.0
2018-10-15T21:04:36.213Z
It is unfortunate that all the common examples of polymorphism - Animal, Vehicle, Shape, etc. - are flawed. Maybe someone could collect up some good examples instead? There used to be a Question here about that.
Scott Rowe
CC BY-SA 4.0
2018-10-15T21:08:07.133Z
@ScottRowe, most of those can be made to work for interface polymorphism, but not for concrete (class) polymorphism. Note that the typical hierarchy of the animal kingdom is all abstract concepts. Mammal can't be instantiated, nor can Vertebrate. Only the "leaf" nodes represent actual animals.
Buffy
CC BY-SA 4.0
2018-10-15T23:55:44.587Z
Actually, there is no need to start at gates and low level stuff. But if you teach OO really really badly your students won't advance very far. My experience is quite long and deep. Note that people teaching functional programming are very unlikely to start at bits and bytes. But in general, if you want to teach something well, learn it _and_ its pedagogy. Don't just try to force fit it.
Buffy
CC BY-SA 4.0
2018-10-13T22:07:55.010Z
2018-10-15T17:52:08.653Z
2018-10-15T17:52:08.653Z
Buffy
<p>So as not to confuse issues, let me give more detailed advice here on why the students are going wrong and about their mental model. I'll try to keep this distinct from the problems of what I consider a poor example of subclassing. </p>

<p>The first lesson that you need to give them is the distinction between a message and a method. A method is the implementation some actions or information request. A message is the invocation of those actions. Methods are defined in classes. Messages are sent to objects generally via a variable of some kind. Be clear about the terminology. Don't say function (except static methods). Don't say "call a method". Say "send a message". Just as you would IRL. Language is important. If you want students to have a good mental model, use appropriate language. If you use the language of C, they will think like C programmers, but OO isn't like that. </p>

<p>The second lesson is that objects receive messages and every message is interpreted <em>by the object</em> that receives it in terms of its own <em>most specific</em> class. It doesn't matter which variable refers to it, or the declared type of the variable (so long as it is legal). The interpretation of the message is specific to the object. </p>

<p>The third lesson is that the "system" knows different things at compile time and at run time. At compile time it only knows the declared types of things, not the actual types. At run time the system "knows" the actual type of an object being referred to (more accurately, an object knows its own type). But objects are only created at run time. At compile time, all we have is the text of the program. </p>

<p>The fourth lesson is that variables don't "hold" values. Variables <em>reference</em> values. You can actually take this view even for int values without loss. The implementation is immaterial to a valid mental model. An int variable refers to an int. It can later refer to a different int. "Holding" has no place here. This makes the reference model of objects much easier to grok. </p>

<p>The fifth lesson is that objects get a type only when they are created. The same is true for all values, actually. Moreover, no value ever <em>changes</em> its type. Its type is immutable as long as it is in existence. </p>

<p>Putting lessons 4 and 5 together, a variable can <em>refer</em> to different objects at different times (when legal in the type system). But no value changes its type, nor does the variable change its (declared) type. </p>

<p>The reason for declaring variables to have a type and to give values a type at creation is to avoid a large set of programmer errors as you create the program so they don't have to be caught (or missed) at run time. Other languages (Python, Ruby) don't give a declared type to variables, so there are a larger number of potential errors that can escape if testing isn't rigorous. </p>

<p>I think these rules are sufficient to dispel the variable mismatch issues in the question asked here, but can extend if comments make it necessary. </p>

<hr>

<p>On the question of language and especially the notion of a "message" vs a "call". </p>

<p>In languages like C one "calls" a function. And in languages like Java, one sends a "message" to an object requesting a service. The actual mechanism for this is quite different. </p>

<p>In C, one can examine the text of the program and determine precisely what will happen when a function is called. The "dispatch" of the function is direct - a sort of direct goTo. Note the words "determinable from the <em>text</em> of the program." </p>

<p>In Java you cannot in principle know precisely which method will be dispatched when you send a message as this depends on the specific type of the object that receives the message, not on the text of the message (the text of the program). Of course if the program uses no polymorphism at all, so that the specific type to which every variable refers is known then than won't be true, but in general if object A and B both implement interface I, then x.mumble(3) can be different depending on whether, at that run time instant, x refers to an A or to a B. Therefore you can't "call" methods (other than static methods) of A or B, you can only send a message to the object referred to that you would like service "mumble". </p>

<p>If you ignore this, then polymorphism will be <em>much</em> harder to understand. Since the mechanism is different, different language is called for and appropriate. </p>

<p>To respond directly to the comment that generated this addendum, no, you don't "send a message to a knife to cut". YOU cut with the knife. The knife isn't an actor here. You are and only you. But if you had a household of service robots you would send messages to them since they are actors that "know" how to carry out their own actions. "Daneel, cut the bread." is a message. The robot knows how to cut, but Charlee might cut differently (say with a laser). Here you use messages. </p>

<p>Ultimately you want to be able to think in a language. If you use misleading terminology (leading you to think that you have more "control" than you really do), then you will just confuse yourself. </p>

<p>For a specific example. Suppose you have a Set (with A, B, and I) taken from above. Now you iterate over the set and send "mumble(t)" to each element. Different things happen and the text of the program doesn't tell you what will happen other than that it is <em>some</em> implementation of a method defined in I - not the explicit method. The objects are in control. The receiver of a message, not the sender, is in control. Request a service - send a message. Dispatch is indirect via the object, not direct from the code invoking the service. </p>

CC BY-SA 4.0
2018-10-15T17:41:28.590Z
These are all great points, and after some discussions with students today, I think the compile time/run time point is the biggest issue, as my slides are very clear about producing a good mental model on the other points (i.e., a variable of type X references an object of type Y where Y extends X), and _most_ students seem to get that. Eclipse is the IDE of choice starting in CS2, but they don't seem to quite grok what the computer knows when. I'll have to see about squeezing in a longer discussion on that, probably next semester.
cryptic_star
CC BY-SA 4.0
2018-10-29T21:15:32.310Z
I personally find the term "message" to be both unnecessary and misleading. It doesn't align with my perception of real life at all. I don't send messages to my knife when I want to slice bread. I execute some action on the knife and bread. For me "method call" seems to be closer both to underlying logic and to real life analogy.
Frax
CC BY-SA 4.0
2018-10-30T00:10:11.013Z
@Frax, actually you are quite mistaken. I'll add an annex to my answer to explain why.
Buffy
CC BY-SA 4.0
2018-10-30T10:32:23.120Z
@Frax https://softwareengineering.stackexchange.com/q/46642/275652
Ben I.
CC BY-SA 4.0
2018-10-30T18:15:05.660Z
I don't think I'm mistaken. I know very well how Java methods work. Yet I very much prefer to think about them as abstracted switch statements. The fact is, that in vast majority of cases you know very well what is going to happen, and all that "object is in control" OO-speak is kind of moot. Actually, my Object Programming course presented switch statements and inheritance side-by-side, simply as different solutions to the same problem, with different trade-offs (cheap new methods versus cheap new behaviors).
Frax
CC BY-SA 4.0
2018-10-15T17:10:03.300Z
2018-10-30T00:27:04.457Z
2018-10-30T00:27:04.457Z
Buffy
<p>I notice you expressed your concerns without once using the word 'pointer' (or even 'reference'). This may be a problem. You also talk about v = b meaning "b is stored in v", but that's not really what this means. It means the pointer "v" gets overwritten by the pointer "b", which is a pointer to the object "b." (b-dot). The object doesn't "fit inside" its pointer. I'm nitpicking here because although Java calls its implicit smart pointers 'references', they are pointers and this concept is essential to grasp in understanding their behavior.</p>

<p>Primarily, students need to learn that any non-primitive Java variable, which is a pointer, is a completely different entity from the object it points to. These two things are separate: they're created in separate places in code, they mean very different things when you use them, and they can have different types.</p>

<p>I usually illustrate this by drawing the pointer as a triangle, labeling it with its type above and its variable name (if it isn't anonymous) below. The object I draw as a circle with its type above and its object name (variable-dot) below, and I illustrate the abstract value of the object in the circle.</p>

<p>For example, if I have an Set&lt;Integer> pointer called foo, the type of foo is pointer to Set&lt;Integer> (though I'd generally just say that aloud and label it Set&lt;Integer>) and the name of foo is foo. The type of the object might be HashSet&lt;Integer>, and its name would be "foo." as in "foo-dot". This is because when you use the dot operator in Java, it automatically gives you the object. Any time you omit the dot you're talking about the pointer, and anytime you use . you're talking about the object. So "foo." is the literal name of that object (or one literal name, if it has aliases).</p>

<p>Object types must be class types, but the pointer type can be any supertype of the object type because (for example) a HashSet&lt;Integer> is a <em>kind</em> of Set&lt;Integer>. Thus, it's still type-safe for a pointer of that type to point to an object of that type: HashSet&lt;Integer> must contain all of the methods described in Set&lt;Integer>, so any method we can call on the pointer will have a corresponding body in the object (provided the pointer is not pointing to null).</p>

CC BY-SA 4.0
2018-11-03T15:45:19.967Z
I think I must have missed something. How would this help the students understand why a Bicycle *can* fit into a Vehicle variable, but String cannot?
Ben I.
CC BY-SA 4.0
2018-11-02T11:52:03.567Z
2018-11-02T11:52:03.567Z
Trixie Wolf
<p>There is yet another flaw indicated in the code as presented, but it is of a different kind, so I've separated this out into a separate answer. One of the principles of good OO design is called "Tell, don't Ask". </p>

<p>What this means is that whenever possible, we should tell an object to do something to advance our computation rather than asking it for the information we need in order to advance that computation elsewhere. Generally, void methods are of the <em>tell</em> variety, and others are of the <em>ask</em> kind. In the sample code, the drive method tells a Vehicle to do something. This is fine. What it does is determined by its own class and by arguments in the method (here none). </p>

<p>But the <em>honkHorn</em> method doesn't tell a Bicycle to honk its horn. It asks for a piece of information (a String) that might be used elsewhere in the program to indicate the sound of a program. The Bicycle, itself, does no honking. </p>

<p>If you do this sort of thing a lot - gather information from objects and act on that information - what it means is that the actual behavior of the program is distributed around the program, where it can be harder to maintain than if it is localized within the objects. </p>

<p>Not every program can avoid such accessor methods altogether (nor should that be a goal for most programs), but, when you consider adding an accessor to a class, try to decide if the locus of the action shouldn't better be within the object itself, rather than somewhere, maybe not yet determined, else in the program. Tell the objects to do your bidding. Don't just treat them as convenient data stores with the logic elsewhere. </p>

CC BY-SA 4.0
2018-10-16T23:40:56.357Z
2018-10-17T13:51:16.297Z
2018-10-17T13:51:16.297Z
Buffy
<p>This is only a partial answer, and it is aiming at doing something very practical in your classroom right away.</p>

<p>I rather liked the old GridWorld case study from AP Computer Science for this, as there were various sorts of <code>Actor</code>s, all of whom had their own <code>act()</code> method.  (This is also the approach used in GreenFoot.)  </p>

<p>It allowed you to create an <code>ArrayList&lt;Actor&gt;</code> and add many different Actors.  <code>Rock</code>s, <code>Flower</code>s, <code>Critter</code>s, etc, and then loop through your list and just run <code>act()</code>.</p>

<p>You can quickly imitate, in a very silly way, something similar using an <code>ArrayList</code>.  The code is ridiculous, but in terms of exploring the simple nuts-and-bolts of upcasting, downcasting, type, and polymorphism, it's actually a great example.  </p>

<p>The fact that it works at all already gives students an immediate sense of what is happening.  I'd present them with the code, and ask them to predict what it will do.  Then run it a few times, and begin to ask them questions like, "Why does this work at all?" And "Could I call <code>.length()</code> on the items in <code>silliness</code>? Why or why not?" And "Given the code you're seeing here, could you imagine a legitimate reason to group different sorts of Objects together?"  And "Why do the Objects all print different things to the screen, even though silliness only thinks that they are <em>Objects</em>, not Strings or arrays or whatever?"</p>

<pre><code>ArrayList&lt;Object&gt; silliness = new  ArrayList&lt;Object&gt;();
for (int i = 0; i &lt; 10; i++)
    silliness.add(nextObject());
for (Object mystery : silliness)
    System.out.println(mystery);

// . .. . . . elsewhere...

public Object nextObject(){
    Random rand = new Random();
    int randomNum = rand.nextInt(4);
    if(randomNum == 0)
        return new int[10];
    else if(randomNum == 1)
        return new String("Silly String!");
    else if(randomNum == 2)
        return new ArrayList&lt;Integer&gt;();
    else
        return new Integer(31415);
}
</code></pre>

<p>This code, as ridiculous as it is, gives a nice, simple touch-point in your discussions with students throughout the unit that can help them make sense of the polymorphic behaviors.</p>

CC BY-SA 4.0
2018-10-18T01:39:18.823Z
I think this is a fine exercise to use in that it will avoid any preconceived notions of how the `object` should act based on its name. I does, indeed, form a good touch-point if used. Unfortunately, for me, it doesn't seem to directly address the OP's current problem. It can probably help to avoid the problem in the next term however, so it does have value.
Gypsy Spellweaver
CC BY-SA 4.0
2018-10-18T02:28:55.817Z
@GypsySpellweaver I respectfully disagree, I think it's immediately practical. OP already acknowledged that they need to reteach at this point, which is why I went for a clarifying nuts and bolts example.
Ben I.
CC BY-SA 4.0
2019-01-15T19:22:09.540Z
@BenI. This example is a good point. I did used to use the common example of an abstract Shape class that has various concrete subclasses (e.g., Oval, Rectangle), and then a data structure that contains Shape objects and prints out the name of the shape, area, etc. It does give some good intuition about how it all works.
cryptic_star
CC BY-SA 4.0
2018-10-16T13:39:46.870Z
2018-10-16T13:39:46.870Z
Ben I.
<p>I'm not so surprised that people struggle with something like <code>Bicycle b = new Bicycle(); Vehicle v = b;</code>. It is not a very practical example, and it doesn't really dictate what behavior you would expect. What about using more realistic and practical example(s)?</p>

<p>You can use some examples from <a href="https://cseducators.stackexchange.com/q/4689/4884">this question</a>. <a href="https://cseducators.stackexchange.com/a/4702/4884">My answer there</a> describes implementation of arithmetic expressions. This was one of the examples used in my Object Programming course, and I think it's an excellent one (I list its advantages in the answer). Of course Java implementation would look differently and would use actual inheritance.</p>

<p>I think that basics of inheritance and methods dispatch are actually very simple and intuitive (if you have a Bicycle, why would you expect to <em>not</em> behave like a bicycle?), but not very easy to describe in words, or on abstract examples. My general idea is that you should first build the expectations for a mechanism that behaves in particular way, and then present inheritance as fulfillment of this expectation. In other words, you first build the mental model, and only then give it a name. Otherwise you risk that people will first create wrong mental model that will be hard to fix.</p>

<p>One approach would be to actually implement these arithmetic expressions using one class with enum type tag and switch statements or ifs. It is easily demonstrable, that this approach is pretty inflexible (and rather ugly), and that it would be useful to give it a structure in which method implementations are grouped by behavior. I believe at this point explaining interfaces/inheritance should be easier, as you have a tangible problem which they solve.</p>

<p>Disclaimer: I don't have any measurable experience in using this approach, but I think I have seen it working (while studying myself).</p>

CC BY-SA 4.0
2018-10-31T17:49:09.620Z
2018-10-31T17:49:09.620Z
Frax
<p>This discussion of the design of the code is a worthwhile one to have. However, regardless of ones opinion, one is likely to encounter code which follows this pattern. Therefore, it is important to understand what is happening.</p>

<p>The line <code>Vehicle v = b;</code> is giving an alternate name to the <strong>same</strong> object. Additionally, it is saying <em>"v, you are a bicycle, but I am going to treat you as an ordinary vehicle. I will ignore anything special about you."</em> As a result, any method of <code>Vehicle</code> that <code>Bicycle</code> overrides will be honored. However, I will not call any of your <code>special</code> methods. The compiler enforces this by generating the error.</p>

<p>This is exactly what happens when you declare the type of a variable to be an <code>interface</code>. You are promising only to invoke the methods defined by that <code>interface</code>.</p>

CC BY-SA 4.0
2018-10-31T15:55:29.767Z
2018-10-31T15:55:29.767Z
Fritz Sieker
<p>I'm finding that my CS2 students really struggle with the notions of type conformance and subtype polymorphism in Java. Say we have the following:</p>

<pre><code>public abstract class Vehicle {
    // attributes + constructor
    public void ride() { ... }
    public String toString() { ... }
}

public class Bicycle extends Vehicle {
    // attributes + constructor
    // notice this is an override from Vehicle
    public void ride() { ... }
    public String honkHorn() { ... }
}
</code></pre>

<p>They then consider the following problems, with my commentary on common mistake(s) following each problem:</p>

<pre><code>Bicycle b = new Bicycle();
Vehicle v = b;
</code></pre>

<p>Students look at this and think <code>b</code> cannot be stored in <code>v</code>, either due to the type difference, or maybe because <code>Bicycle</code> has a constructor with a different number of parameters than the <code>Vehicle</code> constructor, so of course <code>b</code> can't 'fit' inside <code>v</code>.</p>

<pre><code>Bicycle b = new Bicycle();
Vehicle v = b;
v.ride();
</code></pre>

<p>Students commonly think that the <code>ride</code> method in <code>Vehicle</code> will be called. I understand why this mistake is made, but those who get this correct still struggle then with this next problem:</p>

<pre><code>Bicycle b = new Bicycle();
Vehicle v = b;
v.honkHorn();
</code></pre>

<p>Students now think this is also syntactically valid. Because subtype polymorphism ensures that the method call will use the object's implementation, rather than the variable's, they think that Java will somehow recognize that <code>v</code> is storing an object of type <code>Bicycle</code>, and thus <code>honkHorn</code> is available to be called. It never occurs to them that <code>Vehicle</code> doesn't even have this method, so of course it won't work.</p>

<p>Anyway, they have had two quizzes and now an exam involving these concepts (despite seeing them in class contextualized in other learning material all semester, and theoretically a little at the end of last semester), and a significant number of students are still struggling with this. Any suggestions on how to convey all these concepts? My approach is usually to convey very clear models of how things look in memory, but that doesn't seem sufficient here. Do I just need lots of examples/practice problems? Other suggestions?</p>

<java><object-oriented-paradigm><polymorphism>
Mental Model of Type Conformance/Subtype Polymorphism
# Mental Model of Type Conformance/Subtype Polymorphism

(Asked by: username_0 on 2018-10-13)

I'm finding that my CS2 students really struggle with the notions of type conformance and subtype polymorphism in Java. Say we have the following:
public abstract class Vehicle {
    // attributes + constructor
    public void ride() { ... }
    public String toString() { ... }
}

public class Bicycle extends Vehicle {
    // attributes + constructor
    // notice this is an override from Vehicle
    public void ride() { ... }
    public String honkHorn() { ... }
}

They then consider the following problems, with my commentary on common mistake(s) following each problem:
Bicycle b = new Bicycle();
Vehicle v = b;

Students look at this and think b cannot be stored in v, either due to the type difference, or maybe because Bicycle has a constructor with a different number of parameters than the Vehicle constructor, so of course b can't 'fit' inside v.
Bicycle b = new Bicycle();
Vehicle v = b;
v.ride();

Students commonly think that the ride method in Vehicle will be called. I understand why this mistake is made, but those who get this correct still struggle then with this next problem:
Bicycle b = new Bicycle();
Vehicle v = b;
v.honkHorn();

Students now think this is also syntactically valid. Because subtype polymorphism ensures that the method call will use the object's implementation, rather than the variable's, they think that Java will somehow recognize that v is storing an object of type Bicycle, and thus honkHorn is available to be called. It never occurs to them that Vehicle doesn't even have this method, so of course it won't work.
Anyway, they have had two quizzes and now an exam involving these concepts (despite seeing them in class contextualized in other learning material all semester, and theoretically a little at the end of last semester), and a significant number of students are still struggling with this. Any suggestions on how to convey all these concepts? My approach is usually to convey very clear models of how things look in memory, but that doesn't seem sufficient here. Do I just need lots of examples/practice problems? Other suggestions?

**Tags:** java, object-oriented-paradigm, polymorphism


---

## 7 answers

### Answer by username_1 on 2018-10-13. Score: 3

The problem is that you don't really have subtype polymorphism here. While the language permits it, it is poor practice to change the interface (set of public methods) as you move down the hierarchy. I'm not speaking of the formal *interface* but only of the messages that an object is allowed to handle. Your class Vehicle doesn't have honkHorn, but a subclass does.

The problem with this is that if I have an object, I need to know its specific type to know what methods it supports. Some Vehicles support honkHorn, but others don't so I need to test.

This is, at best, ad-hoc polymorphism.

If you want true subtype polymorphism define a class as an interface or abstract class as you have done here, but all subclasses should exhibit exactly the same interface.

Then, if you define a variable to have the interface (abstract class) type, then it can refer to any object of any subclass and it can field any message defined at the top level. You *never* need to ask instanceof and you never need to cast.

It is, of course, harder to build a system keeping such a pure rule, but it can be done and it saves you a ton of grief later.

One of the reasons we want to build OO software is to let the system figure things out without explicit testing. If you change "interfaces" within hierarchies you are just back to ad-hoc decision making. You are defeating the notion of IS-A that the OO paradigm was built for.

In your example you can't really say that a Bicycle IS-A Vehicle. You can say that it is a Vehicle, but something more, and we have to determine what by ad-hoc means in many instances. Sometimes by declaring variables to have a specific type (rather than a general type) and sometimes by testing.

In terms of "contracts", if you change the contract as you come down the hierarchy, it wasn't really a contract.

Sadly, too many books don't understand this and define meaningless, and difficult to work with, "hierarchies".

One way to avoid this issue, is to define Vehicle as an interface and then define Bicycle as another interface that extends Vehicle. Now your intent is clear. Classes implementing an interface have *only* the public methods defined in their interface and nothing more. Now you have interfaces of *concepts* which is what they are really intended to model, and classes of *objects* that conform to specific concepts. This may be the mental model you seek, actually.

---

I discussed Polymorphism at some length here: <https://cseducators.stackexchange.com/a/4050/1293>

---

Let me add some things here to point to a better way. One of the lessons is that subclassing is generally overused. Some books present it as the "really big thing". Instead, programming by composition is much more valuable. When you create a class give it parts that are instances of some other, simpler, class.

For the immediate problem here. Give Vehicle a method *makeSound*. Give each subclass of it an instance field that refers to some kind of object that might make a typical sound. For a bicycle object it might be a Horn object. Then when any vehicle is sent the makeSound message it *delegates* the making of the sound to the object that is part of its composition. Delegation is the big idea here. Now you don't need to change the protocol in different classes. Just change the implementation, but giving different "parts" to different vehicles.

At least one very commonly used book has something like the following hierarchy. First a Point class. A point has some coordinates. Then, for the first (ugh) example of subclassing is a Circle class. This is "easy" to write, since if you subclass Point all you need to add is a radius value. But to a mathematician, is every circle a specialization of point? It is backwards, of course. Taking it farther, a Cylinder can subclass Circle just by adding a height value. This makes it very easy to type in, but very foolish, both mathematically and from a program design standpoint. If you create a Cylinder, what sort of variable should you use to refer to it. If you don't use a Cylinder variable, then within the next few lines you are very likely to have to cast the variable, or, if you have put such things into a List then you are going to have to type case them (or equivalent) when you look at them again. Don't do that. But what *can* you do better. Use delegation.

When you build your Circle class, don't make it an extension of Point. Instead, give it an instance variable of type Point. A Circle is a different kind of thing. It isn't a point, but it HAS-A point as a field.

Likewise the Cylinder HAS-A Circle for its base. Much cleaner. The cylinder delegates some of its actions to its base when it receives a message. Likewise the base (a Circle) delegates some messages to its location (a Point).

Now you have a defensible design, but it might not have used subclassing at all. You get reuse (via delegation) and don't confuse the nature of things and require ad-hoc decision making throughout a long program.

> **Comments:**
> **username_0**: This is a really interesting perspective, and something I have never heard in years of schooling. (which perhaps says something about the schooling) I always heard the oft-touted "superclasses define commonalities, subclasses define differences" model. I'm going to have to sit on this and ponder it. If I'm understanding this correctly, your perspective suggests that a non-abstract class should never extend another non-abstract class. Is this correct? Do you have any readings for me to pursue this further?  
> **username_1**: Not exactly. You can extend a class without adding to it's public interface. You can add all of the private methods you like and you can change the behavior - to (hopefully) more specific behavior. So, a Snake can _bite_. A RattleSnake can also _bite_ but it is more serious.  
> **username_1**: Think about whether you gain anything with your hierarchy over having Vehicle and Bicycle completely separate classes. Very little, other than typing (hitting keys), I think. And you avoid most of the traps. It isn't typing (hitting keys) that makes programming hard.  
> **username_2**: A horn is a decorator, as is a signal light, or an arm signal.  
> **username_1**: Well, @username_2, maybe not exactly, but something like that. Use delegation, not inheritance, for such things. But yes, see the Decorator Design Pattern.  
> **username_0**: @username_1 Thank you both for the info. I'm going to ponder it, and I might be back here with more questions.  
> **username_3**: @username_1 A rattlesnake can also *rattle*, though.  
> **username_1**: @BenI. and if you add that in a subclass then you have a bad design. You need to, then, make ad-hoc decisions about what you have - the very thing OO is designed to make unnecessary. Rethink your hierarchy. A sloppy design will pay you dividends later - in pain.  
> **username_1**: A remarkably bad design Point has a subclass Circle (just add a radius), which has a subclass Cylinder (just add a height). So now, every  cylinder is just a point. If you have a variable w/ type Point, what can you do with it? BTW, in at least one book, this is treated as GOOD design. If you need to know the most specific type of an object, then the hierarchy does you no good at all. It is just noise that you may as well omit. The system can no longer help you and you need it all in your head at every statement.  
> **username_1**: @BenI., maybe think of it this way. Is a snake that _doesn't_ rattle, a more general kind of snake or just a _different_ kind of snake? If your snake hierarchy needs warning sounds add them at the top. Now you can distinguish by behavior, not by interface.  
> **username_4**: It is unfortunate that all the common examples of polymorphism - Animal, Vehicle, Shape, etc. - are flawed. Maybe someone could collect up some good examples instead? There used to be a Question here about that.  
> **username_1**: @ScottRowe, most of those can be made to work for interface polymorphism, but not for concrete (class) polymorphism. Note that the typical hierarchy of the animal kingdom is all abstract concepts. Mammal can't be instantiated, nor can Vertebrate. Only the "leaf" nodes represent actual animals.  
> **username_1**: Actually, there is no need to start at gates and low level stuff. But if you teach OO really really badly your students won't advance very far. My experience is quite long and deep. Note that people teaching functional programming are very unlikely to start at bits and bytes. But in general, if you want to teach something well, learn it _and_ its pedagogy. Don't just try to force fit it.  

---

### Answer by username_1 on 2018-10-15. Score: 3

So as not to confuse issues, let me give more detailed advice here on why the students are going wrong and about their mental model. I'll try to keep this distinct from the problems of what I consider a poor example of subclassing.

The first lesson that you need to give them is the distinction between a message and a method. A method is the implementation some actions or information request. A message is the invocation of those actions. Methods are defined in classes. Messages are sent to objects generally via a variable of some kind. Be clear about the terminology. Don't say function (except static methods). Don't say "call a method". Say "send a message". Just as you would IRL. Language is important. If you want students to have a good mental model, use appropriate language. If you use the language of C, they will think like C programmers, but OO isn't like that.

The second lesson is that objects receive messages and every message is interpreted *by the object* that receives it in terms of its own *most specific* class. It doesn't matter which variable refers to it, or the declared type of the variable (so long as it is legal). The interpretation of the message is specific to the object.

The third lesson is that the "system" knows different things at compile time and at run time. At compile time it only knows the declared types of things, not the actual types. At run time the system "knows" the actual type of an object being referred to (more accurately, an object knows its own type). But objects are only created at run time. At compile time, all we have is the text of the program.

The fourth lesson is that variables don't "hold" values. Variables *reference* values. You can actually take this view even for int values without loss. The implementation is immaterial to a valid mental model. An int variable refers to an int. It can later refer to a different int. "Holding" has no place here. This makes the reference model of objects much easier to grok.

The fifth lesson is that objects get a type only when they are created. The same is true for all values, actually. Moreover, no value ever *changes* its type. Its type is immutable as long as it is in existence.

Putting lessons 4 and 5 together, a variable can *refer* to different objects at different times (when legal in the type system). But no value changes its type, nor does the variable change its (declared) type.

The reason for declaring variables to have a type and to give values a type at creation is to avoid a large set of programmer errors as you create the program so they don't have to be caught (or missed) at run time. Other languages (Python, Ruby) don't give a declared type to variables, so there are a larger number of potential errors that can escape if testing isn't rigorous.

I think these rules are sufficient to dispel the variable mismatch issues in the question asked here, but can extend if comments make it necessary.

---

On the question of language and especially the notion of a "message" vs a "call".

In languages like C one "calls" a function. And in languages like Java, one sends a "message" to an object requesting a service. The actual mechanism for this is quite different.

In C, one can examine the text of the program and determine precisely what will happen when a function is called. The "dispatch" of the function is direct - a sort of direct goTo. Note the words "determinable from the *text* of the program."

In Java you cannot in principle know precisely which method will be dispatched when you send a message as this depends on the specific type of the object that receives the message, not on the text of the message (the text of the program). Of course if the program uses no polymorphism at all, so that the specific type to which every variable refers is known then than won't be true, but in general if object A and B both implement interface I, then x.mumble(3) can be different depending on whether, at that run time instant, x refers to an A or to a B. Therefore you can't "call" methods (other than static methods) of A or B, you can only send a message to the object referred to that you would like service "mumble".

If you ignore this, then polymorphism will be *much* harder to understand. Since the mechanism is different, different language is called for and appropriate.

To respond directly to the comment that generated this addendum, no, you don't "send a message to a knife to cut". YOU cut with the knife. The knife isn't an actor here. You are and only you. But if you had a household of service robots you would send messages to them since they are actors that "know" how to carry out their own actions. "Daneel, cut the bread." is a message. The robot knows how to cut, but Charlee might cut differently (say with a laser). Here you use messages.

Ultimately you want to be able to think in a language. If you use misleading terminology (leading you to think that you have more "control" than you really do), then you will just confuse yourself.

For a specific example. Suppose you have a Set (with A, B, and I) taken from above. Now you iterate over the set and send "mumble(t)" to each element. Different things happen and the text of the program doesn't tell you what will happen other than that it is *some* implementation of a method defined in I - not the explicit method. The objects are in control. The receiver of a message, not the sender, is in control. Request a service - send a message. Dispatch is indirect via the object, not direct from the code invoking the service.

> **Comments:**
> **username_0**: These are all great points, and after some discussions with students today, I think the compile time/run time point is the biggest issue, as my slides are very clear about producing a good mental model on the other points (i.e., a variable of type X references an object of type Y where Y extends X), and _most_ students seem to get that. Eclipse is the IDE of choice starting in CS2, but they don't seem to quite grok what the computer knows when. I'll have to see about squeezing in a longer discussion on that, probably next semester.  
> **username_5**: I personally find the term "message" to be both unnecessary and misleading. It doesn't align with my perception of real life at all. I don't send messages to my knife when I want to slice bread. I execute some action on the knife and bread. For me "method call" seems to be closer both to underlying logic and to real life analogy.  
> **username_1**: @username_5, actually you are quite mistaken. I'll add an annex to my answer to explain why.  
> **username_3**: @username_5 https://softwareengineering.stackexchange.com/q/46642/275652  
> **username_5**: I don't think I'm mistaken. I know very well how Java methods work. Yet I very much prefer to think about them as abstracted switch statements. The fact is, that in vast majority of cases you know very well what is going to happen, and all that "object is in control" OO-speak is kind of moot. Actually, my Object Programming course presented switch statements and inheritance side-by-side, simply as different solutions to the same problem, with different trade-offs (cheap new methods versus cheap new behaviors).  

---

### Answer by username_3 on 2018-10-16. Score: 1

This is only a partial answer, and it is aiming at doing something very practical in your classroom right away.
I rather liked the old GridWorld case study from AP Computer Science for this, as there were various sorts of Actors, all of whom had their own act() method.  (This is also the approach used in GreenFoot.)  
It allowed you to create an ArrayList and add many different Actors.  Rocks, Flowers, Critters, etc, and then loop through your list and just run act().
You can quickly imitate, in a very silly way, something similar using an ArrayList.  The code is ridiculous, but in terms of exploring the simple nuts-and-bolts of upcasting, downcasting, type, and polymorphism, it's actually a great example.  
The fact that it works at all already gives students an immediate sense of what is happening.  I'd present them with the code, and ask them to predict what it will do.  Then run it a few times, and begin to ask them questions like, "Why does this work at all?" And "Could I call .length() on the items in silliness? Why or why not?" And "Given the code you're seeing here, could you imagine a legitimate reason to group different sorts of Objects together?"  And "Why do the Objects all print different things to the screen, even though silliness only thinks that they are Objects, not Strings or arrays or whatever?"
ArrayList silliness = new  ArrayList();
for (int i = 0; i < 10; i++)
    silliness.add(nextObject());
for (Object mystery : silliness)
    System.out.println(mystery);

// . .. . . . elsewhere...

public Object nextObject(){
    Random rand = new Random();
    int randomNum = rand.nextInt(4);
    if(randomNum == 0)
        return new int[10];
    else if(randomNum == 1)
        return new String("Silly String!");
    else if(randomNum == 2)
        return new ArrayList();
    else
        return new Integer(31415);
}

This code, as ridiculous as it is, gives a nice, simple touch-point in your discussions with students throughout the unit that can help them make sense of the polymorphic behaviors.

> **Comments:**
> **username_7**: I think this is a fine exercise to use in that it will avoid any preconceived notions of how the `object` should act based on its name. I does, indeed, form a good touch-point if used. Unfortunately, for me, it doesn't seem to directly address the OP's current problem. It can probably help to avoid the problem in the next term however, so it does have value.  
> **username_3**: @GypsySpellweaver I respectfully disagree, I think it's immediately practical. OP already acknowledged that they need to reteach at this point, which is why I went for a clarifying nuts and bolts example.  
> **username_0**: @BenI. This example is a good point. I did used to use the common example of an abstract Shape class that has various concrete subclasses (e.g., Oval, Rectangle), and then a data structure that contains Shape objects and prints out the name of the shape, area, etc. It does give some good intuition about how it all works.  

---

### Answer by username_5 on 2018-10-31. Score: 1

I'm not so surprised that people struggle with something like `Bicycle b = new Bicycle(); Vehicle v = b;`. It is not a very practical example, and it doesn't really dictate what behavior you would expect. What about using more realistic and practical example(s)?

You can use some examples from [this question](https://cseducators.stackexchange.com/q/4689/4884). [My answer there](https://cseducators.stackexchange.com/a/4702/4884) describes implementation of arithmetic expressions. This was one of the examples used in my Object Programming course, and I think it's an excellent one (I list its advantages in the answer). Of course Java implementation would look differently and would use actual inheritance.

I think that basics of inheritance and methods dispatch are actually very simple and intuitive (if you have a Bicycle, why would you expect to *not* behave like a bicycle?), but not very easy to describe in words, or on abstract examples. My general idea is that you should first build the expectations for a mechanism that behaves in particular way, and then present inheritance as fulfillment of this expectation. In other words, you first build the mental model, and only then give it a name. Otherwise you risk that people will first create wrong mental model that will be hard to fix.

One approach would be to actually implement these arithmetic expressions using one class with enum type tag and switch statements or ifs. It is easily demonstrable, that this approach is pretty inflexible (and rather ugly), and that it would be useful to give it a structure in which method implementations are grouped by behavior. I believe at this point explaining interfaces/inheritance should be easier, as you have a tangible problem which they solve.

Disclaimer: I don't have any measurable experience in using this approach, but I think I have seen it working (while studying myself).


---

### Answer by username_8 on 2018-10-31. Score: 1

This discussion of the design of the code is a worthwhile one to have. However, regardless of ones opinion, one is likely to encounter code which follows this pattern. Therefore, it is important to understand what is happening.

The line `Vehicle v = b;` is giving an alternate name to the **same** object. Additionally, it is saying *"v, you are a bicycle, but I am going to treat you as an ordinary vehicle. I will ignore anything special about you."* As a result, any method of `Vehicle` that `Bicycle` overrides will be honored. However, I will not call any of your `special` methods. The compiler enforces this by generating the error.

This is exactly what happens when you declare the type of a variable to be an `interface`. You are promising only to invoke the methods defined by that `interface`.


---

### Answer by username_6 on 2018-11-02. Score: 0

I notice you expressed your concerns without once using the word 'pointer' (or even 'reference'). This may be a problem. You also talk about v = b meaning "b is stored in v", but that's not really what this means. It means the pointer "v" gets overwritten by the pointer "b", which is a pointer to the object "b." (b-dot). The object doesn't "fit inside" its pointer. I'm nitpicking here because although Java calls its implicit smart pointers 'references', they are pointers and this concept is essential to grasp in understanding their behavior.

Primarily, students need to learn that any non-primitive Java variable, which is a pointer, is a completely different entity from the object it points to. These two things are separate: they're created in separate places in code, they mean very different things when you use them, and they can have different types.

I usually illustrate this by drawing the pointer as a triangle, labeling it with its type above and its variable name (if it isn't anonymous) below. The object I draw as a circle with its type above and its object name (variable-dot) below, and I illustrate the abstract value of the object in the circle.

For example, if I have an Set pointer called foo, the type of foo is pointer to Set (though I'd generally just say that aloud and label it Set) and the name of foo is foo. The type of the object might be HashSet, and its name would be "foo." as in "foo-dot". This is because when you use the dot operator in Java, it automatically gives you the object. Any time you omit the dot you're talking about the pointer, and anytime you use . you're talking about the object. So "foo." is the literal name of that object (or one literal name, if it has aliases).

Object types must be class types, but the pointer type can be any supertype of the object type because (for example) a HashSet is a *kind* of Set. Thus, it's still type-safe for a pointer of that type to point to an object of that type: HashSet must contain all of the methods described in Set, so any method we can call on the pointer will have a corresponding body in the object (provided the pointer is not pointing to null).

> **Comments:**
> **username_3**: I think I must have missed something. How would this help the students understand why a Bicycle *can* fit into a Vehicle variable, but String cannot?  

---

### Answer by username_1 on 2018-10-16. Score: 0

There is yet another flaw indicated in the code as presented, but it is of a different kind, so I've separated this out into a separate answer. One of the principles of good OO design is called "Tell, don't Ask".

What this means is that whenever possible, we should tell an object to do something to advance our computation rather than asking it for the information we need in order to advance that computation elsewhere. Generally, void methods are of the *tell* variety, and others are of the *ask* kind. In the sample code, the drive method tells a Vehicle to do something. This is fine. What it does is determined by its own class and by arguments in the method (here none).

But the *honkHorn* method doesn't tell a Bicycle to honk its horn. It asks for a piece of information (a String) that might be used elsewhere in the program to indicate the sound of a program. The Bicycle, itself, does no honking.

If you do this sort of thing a lot - gather information from objects and act on that information - what it means is that the actual behavior of the program is distributed around the program, where it can be harder to maintain than if it is localized within the objects.

Not every program can avoid such accessor methods altogether (nor should that be a goal for most programs), but, when you consider adding an accessor to a class, try to decide if the locus of the action shouldn't better be within the object itself, rather than somewhere, maybe not yet determined, else in the program. Tell the objects to do your bidding. Don't just treat them as convenient data stores with the logic elsewhere.


---

