Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I've been teaching Java to a group of four people for about four months now. Prior to this, they've all had very limited or no other experience programming.

We've gotten through basic control structures and their use and have been able to solve some of the simpler Project Eulers. Things similar to:

int count = 0;

for(int index = 0; index < 1000; index++)
{
        if(index % 3 == 0 || index % 5 == 0)
        {
                count += index;
        }
}


System.out.println(count);

We've also gone over basic object-oriented things such as classes and their uses. However, we have not covered inheritance or polymorphism yet.

I'd like to introduce inheritance and polymorphism together, but I'm not sure how to properly explain polymorphism to someone who's never seen nor heard of it before.

To sum up my question in a few words, I am looking for an effective way to introduce polymorphism to new programmers.

share|improve this question
    
The first Project Euler problem uses a 3, doesn't it, not a 7? –  Joe Z. Jan 7 '13 at 0:40
1  
Joe Zeng: Thanks, just fixed it. –  Zach Latta Jan 7 '13 at 1:10
    
I like the answer which puts emphasizes on the fact that with java you should use inheritance with care if ever. Instead research what problems polymorphism tries to solve ( expression problem) and see different solutions for that aka ad hoc polymorphism. –  AndreasScheinert Jan 7 '13 at 10:11
1  
Unfortunately, due to Java's completely lack of basically every other useful language feature, you pretty much have to use inheritance to solve every problem. –  DeadMG Jan 7 '13 at 19:15

8 Answers 8

up vote 8 down vote accepted

Best to find a real-world example that everybody is familiar with. One of the best I've seen is electrical plug sockets. Polymorphism is how anybody can make a thing with a plug on it, and it'll work in any socket, and inheritance is the actual act of sticking the plug on the end and connecting all the wires and such.

share|improve this answer

You can start with the practical basics and end up with a basic design pattern (such as template method pattern or strategy pattern). The value of teaching though is that the group gets to get their hands dirty in it.

The tricky part is not to let them learn any bad habits; such as breaking encapsulation and using inheritance for everything. This can only be enforced with examples that somehow shows this. Another tricky part is to teach them how to use it practically for day-to-day usage.

Basics

First basic example for inheritance and polymorphism can be, implement a Vehicle that can either be a Car or a Bus. And with all vehicles we can drive() and honk() the horn with them. As you build a list with list with vehicles you can perform the methods on them and see what happens:

public abstract class Vehicle {
    private String name;

    public Vehicle(String name) {
        this.name = name;
    }

    public void drive() {
        System.out.println(name + " is on the move");
    }

    public void honk() {
        System.out.println("The " + name + " honks it's horn");
    }
}

public class Car extends Vehicle {
    public Car() {
        super("car");
    }
}

public class Bus extends Vehicle {
   public Bus() {
        super("bus");
   }

   @override
   public void honk() {
       System.out.println("The bus toots it's horn");
   }     
}

The inheritance part is that every class that extends another inherits it's methods. The polymorphism part is that they both share methods and can be executed without knowing the actual class type. The method to test it all in practice would look something like this:

public static void main(String[] args) {
    ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>();

    vehicles.add(new Car());
    vehicles.add(new Bus());

    for(Vehicle v : vehicles) {
        v.drive();
        v.honk();
    }
}

As a further study, they can try to implement registration numbers so that they're visible in the output. Bonus points if they realize they can do so in the abstract class. Also they can try making the vehicles more personalized, such as a SportsCar goes "vroom" when it's driving.

Depending on the user group you're running, you might want to change the actual types and methods with the one that the group can relate to the most. It's easier to learn something that you easily can relate to. If they're not interested in vehicles, maybe something else will help them understand it.

share|improve this answer
    
Would be helpful to understand the -1 –  Spoike Jan 6 '13 at 10:56
2  
-1 What about airplane or train vehicle? It cannot drive or honk. I don't like this example because it doesn't explain REAL use of polymorphism. For example if someone asks "Why can't we simply have enums and switches instead this 'inheritance'?" –  Euphoric Jan 6 '13 at 10:59
    
@Euphoric: I'd leave that as an exercise for the guy who has to learn it. Why tell them all the details when they should figure it out themselves. For the question with enums and switches: "Today I'm talking about inheritance and polymorphism, you can go ahead and implement it using enums and switches if you want to". –  Spoike Jan 6 '13 at 11:04
1  
@Euphoric: You could go the route of implementing everything first with enums and switches to highlight the problem of code that needs to change in several places, and introduce encapsulation (putting the seperated cases into the same class). The problem is how much time the OP has to explain it all for each session. –  Spoike Jan 6 '13 at 11:14
2  
@Spoike: One issue I have is for a trivial problem the enum/switch solution is actually easier to implement and understand for a novice, so you end up reinforcing (in their minds) that OO is hard and does not actually help solve the problem. You must make the example such that OO is simpler and easier (for the novice) to implement and understand....... –  mattnz Jan 7 '13 at 0:51

Learn what the people you're teaching are interested in, then mention an application of that concept in that field.

An easy way to go around this is game development. Whenever I teach somebody a concept of object-oriented programming, I describe to them how it's used in games, because some people interested in programming are fascinated by video games to some extent.

So, for polymorphism (after I've described inheritance), I describe to them how the engine keeps a list of various game objects for the currently loaded level, all of them being very diverse: cameras, celestial objects, players, lights, power-ups, decoration, triggers, etc. These all have two common functions to perform: a small update for each engine tick (to account for physics, user input, or whatever else each object does) and the rendering part. For each of these functions, it's reasonable to have a method. All these objects have extremely different implementations of these methods (because they are very different kinds of objects). But the main loops of the engine don't need to know about that. They just need to know that there are game objects in memory that will respond to this, resolving the correct functionality by themselves. And I make sure I illustrate how without polymorphism, that would be a nightmare.

share|improve this answer
2  
Almost get -1 for the "most people interested in programming are fascinated by video games", but the example can be as simple or complex as needed, and clearly "if's and enums" can not be used. Virtually all textbook examples of introductory polymorphism, the program would be significantly simpler using an enum/switch (from the perspective of a novice/student)..... –  mattnz Jan 7 '13 at 0:59
    
Well, you're right, it was a hasty overstatement. I've changed it to "some". –  Theodoros Chatzigiannakis Jan 7 '13 at 1:00

Without inheritance:

Dog d = new Dog
d.bark( )

With inheritance:

Animal d = new Dog()
d.doSound( )

Animal c = new Cat()

Programming against supertypes gets you freedom of type at runtime:

Animal x = getAnimal( )
x.doSound( )
share|improve this answer
    
doSound() doesn't make sense at all. It's almost as bad as DoSomething() since most animals who can make sounds can probably make more than one. –  jgauffin Jan 7 '13 at 8:18
    
@jgauffin All abstractions leak, but that doesn't mean one cannot use them within a reasonable scope. This is a good example for teaching polymorphism without getting too exquisite. –  user61852 Sep 4 '13 at 20:21

The section on Polymorphism in the Java Tutorials are all that is needed. I use the Tutorials/trails all the time. As a teacher I just support them when they need help and give assignments to re-enforce there learning.

share|improve this answer

I prefer to show examples that deal with UI.

All controls have some common functions, like draw, common events, and so on. This gets them thinking about polymorphism, inheritance, encapsulation, the works.

share|improve this answer
    
This is a sparse answer but probably one of the better ones, because what's notable about UI controls is that you will want to make new ones, and thus the old switch-case standby breaks down quickly because you can't just go and modify the framework. The most useful examples of polymorphism are those where the base class and (some) derived classes are obviously maintained in different assemblies/packages and probably by different people/groups. –  Aaronaught Sep 4 '13 at 19:54

I would first explain inheritance, using one of the classical inheritance trees (for example a Shape base class, with derived Circle and Rectangle classes), and then introduce polymorphism to show how a function that only knows about the base class can get the behaviour implemented by the derived class.

Although I have stated it as two steps, you can still introduce both concepts in one lecture/session. It is just that polymorphism needs to refer back to inheritance for a proper explanation/understanding.

share|improve this answer
    
Ewww, no. Circle : Shape is quite terrible. –  DeadMG Jan 6 '13 at 20:08
    
@DeadMG: All the classic inheritance examples are terrible. I think this is a lesser one if you also want to teach polymorphism. Just be sure to avoid the real monstrosities like Square : Rectangle –  Bart van Ingen Schenau Jan 7 '13 at 9:44

The most basic form of polymorphism that everybody has been in contact with is arithmetic operations.

add, substract, multiply and divide can be applied to integer, real or complex numbers, and some combinations of them.

The same operations can be extended to vectors and matrices.

You can even imagine ways to apply them on strings (e.g., python: 'foo' + 'bar'*3)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.