I'm trying to teach how an object is just an instance of a class to a
buddy of mine.
IMHO your trouble to teach that to you buddy is, that actually it's incorrect.
No doubt, there are programming languages, where objects can be constructed by instantiating classes. At the same time, in most programming languages that have class objects, class objects are not commonly constructed by instantiation.
The point is: explaining objects using classes is like explaining cars using car factories. Much like the latter is a poor choice to teach driving, the former is a poor choice to teach OOP.
For the sake of using a rather widely spread language, let's illustrate this in JavaScript:
var dog = {
pat: function () { print('woof!'); }
}
var cat = {
pat: function () { print('meow!'); }
}
var peter = {
goodMood: false,
cheerUp: function () { this.goodMood = true; }
pat: function () {
if (this.goodMood) print('thank you!');
else print('put your hands off of me!');
}
}
dog.pat();
cat.pat();
peter.pat();
peter.cheerUp();
peter.pat();
See, we have three distinct objects, without using classes. But we already see the most important things: polymorphism and encapsulation of state.
All this is nice, but what will you do, when you need more that one dog? Wouldn't it be nice to have means to not create every one of them by hand? And still, without actually resorting to classes or prototypes, we can solve this:
var dogBreeder = {
getDog: function (name) {
return {
name: name,
pat: function () { print('woof!'); },
call: function (name) {
if (this.name == name) print('woofwoof!');
else print('rawr!');
}
}
}
}
var steve = dogBreeder.getDog('Steve');
var alan = dogBreeder.getDog('Alan');
While undoubtedly, with most JavaScript implementations the approach above comes down to throwing memory out the window, it introduces the concept of a factory without depending on another addition (such as classes or prototypes). It practically shows the distinction between an entity who's purpose is to provide other entities and the entities it provides.
And now is a good time to talk of classes and the advantages they bring.