It\'s been years since I thought of this, but I am training some real juniors soon and need to explain what an object is to someone who doesn\'t know what it is.
B
I would try starting with actual code. Hopefully they're at least slightly familiar with some language. Write a simple program without using any classes or OO design at all, and then show how it can be made clearer or easier to maintain or whatever, if you redo it using classes.
A good example would probably be something where there are several functions that all use the same set of variables. For example (this is just the first example I could think of. You could probably think of much better ones -- hopefully something that doesn't seem too contrived and resembles something that you would actually write for a real-world project):
void printContactInfo(String name, String address, String phoneNumber) {
System.out.println(name + " lives at " + address + " and his/her phone number is + "phoneNumber");
}
You write the code above, then at some point later, you decide that you'd also like to include the person's email address and username. Or you are dealing with two different people. You could easily end up with unwieldy functions that take several arguments, or have zillions of variables to keep track of. Or you could write a Person class, and you'd just call:
Person someguy = new Person("MatrixFrog", "123 Notareal Street", "555 5555");
someguy.printContactInfo();
Again, probably not the best example. And I do agree with mad-j that these little "car" and "person" examples aren't always great. But I think if you presented the example as a solution to an actual problem that comes up while writing code, it might be clearer.
Same thing with inheritance. The idea is based on the real-world understanding that "An X is a certain type of Y" but the reason we do it is to make code easier to read and write. I don't think I really understood inheritance until the first time I found myself writing two classes with a lot in common, and thinking, "Wait. These have a lot of the same properties. Maybe I should put their common properties into a superclass!"
I would go from Access Levels and Encapsulation and move out from there. Encapsulation is a reasonably simple concept to grasp and has some clear benefits. From there you can talk about abstraction, inheritance and polymorphism quite easily.
As an undergraduate I found Encapsulation to be an good anchoring concept in a quite abstract area.
To a beginner: An object is like a noun. If you're in a classroom then you have desks, students, teacher, projector etc. Each has characterists of their own and some commonalities.
So if we wanted to write a program that would behave in the same way as a classroom, we need to recreate all these 'nouns' in code. Each can do things (student::listen()) and they can interact with each other (student::search(new Desk()))
When we have defined all the rules and behaviours (i.e written our classes/interfaces) then we set them loose in the program. for(i=0;i<30;i++){class.Add(new Student()))} etc
Start with explains what Object-Oriented-Design means...
- It means that you take a real-life situation you want to model using software and copy its model into a software models.
Each entity within the actual situation (the one that exists even if there was no software) gets a representative in the software's design - an object. (Abstraction)
Each kind of entity is a class, every entity of the same kind is an object of the same type.
* Give an example here from a field that interests your students and continue with same example. - Try to make it a funny one.
Each object should model only one entity and that entire entity, if you change one object it should not affect another. (Encapsulation)
Next, you think of the relationships between the entities, is one a specific type of another (inheritance), is one a part of another (composition), can one go in and out of another (aggregation).
Next, you think about the main things the entities do (methods) and how to define them (properties/fields).
Now take an example for inheritance from the example you gave earlier and explain polymorphism - you can do the same thing that you can on the general type as you can on any specific type that inherits it and you can ask every specific type to do what you can ask the generic type to do, but they can do it whatever way they want to (overriding).
Next interfaces, here perhaps use animals - not all animals have tails to wag, but some do. You want to model a man, a dog, a cat, a spider and a dinosaur. All are (or were) animals but the generic type - animal can't wag its tail, a. because there is no such thing as a generic animal (it's abstract) b. because not animals can WagTail(). However, all those that can WagTail() can implement the interface IWagTailable.
Access levels:
if something is part of an entities description or known actions (if it is in its contract) - it's public.
If an object keeps some information that only it needs to know about or is allowed to know about or does something no one knows about - it's private.
If not everyone is allowed to know about it but its inheritors are allowed to know about it - it's protected.
Maybe get into constructors (how to initialize the object's definitions) and destructors (freeing the memory/file handles/connections it's holding).
Maybe also properties - kind of like fields, only you can limit access to read-only, write-only or even make something happen when reading or writing.
I prefer to think of Ants - it gives visual learners something to "see" and you "tell" for the auditory learners. Focus on the WHY for each part first to avoid the glassy eyes.
Ant derives from Insect (Inheritance) Worker Ant, Queen Ant, Drone Ant all derive from Ant (Inheritance). There is no generic “Ant”, all ants are from the derived classes of Worker, Queen etc but they all have the same basic Interface –actions (methods) and Properties.
Worker Ant, Queen ant, Drone Ant derive from Ant and thus exhibit ad-hoc polymorphism where they all derive from the same Ant class and exibit subtyping polymorphism (Inheritance) of the Ant class, these ants are all a subclass of the Ant class and inherit the 6 legs, 2 eyes, 3 body segments etc. of the Ant – the Properties. Ant also has methods, walk, see, and grab ability of the Ant class. Thus the appplication of the implimentation of the Interface of the more generic Ant class (Polymorphism) with the properties and methods of the basic Ant class, but each subclass defines how it implements those.
Worker Ants have different activities and behavior. They Gather food, Protect colony, Dig tunnels, Care for Queen Ant etc but still have the base attributes of Ant (Interface). Jaws are used in each behavior - polymorphic function which is NOT Polymorphism in itself and thus you get the idea of, method overloading for the different use of the Jaws – each method has basic similarity (jaws, grab) but different object types are used – grab dirt, grab other ant, grab food, grab gunk off queen, grab enemy. This shows a WHY of overloading methods, - areas of specialization depending upon what is grabbed – larva (young ants) and food are handled gently and differently than the enemy where we want to rip them up.
Each Worker Ant is an Instance of an ant, separate but with similar behaviors and different task/state at a given time, so given the tasks, they can be on different threads. If one ant on a food-gathering mission (thread) dies, the other ants keep seeking food, as they are not dependant on the dead ants survival.
Each Ant has access and ability to manipulate its own Private attributes, legs, eyes and so forth, but not to manipulate other ants eyes and legs (Access Levels).
Ant Colony – the overall namespace for the Ant – thus the Queen Ant and Worker Ant might belong to the Ant Colony namespace, and the worker ants have access to the Queen Ant but nothing outside does (Protected)
Queen ants never go outside normally – (Access Levels)
Each Ant has access and ability to manipulate its own attributes, legs, eyes and so forth, but not to manipulate other ants eyes and legs (Access Levels). Now this ant knows where its legs are, where it is looking, those are Encapsulated within its instance. The act of Encapsulation creates Abstraction to some degree here.
By using the concept of Encapsulation we can Abstract and thus we can send the Worker Ant off to get food, but we do not have to care how the ant gets the food, only that it returns with food, we have isolated the details of the activity from the result.
You can impliment the examples in the language of choice for your audience. If this helps one person, I am satisfied :). I hope I have not confused myself :)
this question is interesting ... and very complicated ... because it depends on the language you use ...
take objective-c: an object has it's variables, only accessible from inside, and methods, such as accessors ... objective-c actually sends around messages between objects ... which gives comes at a certain cost, but allows lots of cool things, like proxies, mock objects, profiling, AOP and so forth ... in objective-c, a class is an object ... objective-c does not have the notion of access levels ...
take PHP ... there, classes are not objects ... objects have variables and methods ... and it's totally inconsistent ... :) ... just as a bad example ...
take Ruby ... there, everything is completely dynamic ... an object has its variables, only visible from inside, and a class, determining its methods ... you can modify that class at runtime, or even, you can assign a different class to that very object ... funky ... and also, in ruby, operators are methods of objects ... you have incredible language constructs like blocks ...
take ECMA-Script(JavaScript for example) ... here everything is an object ... functions are first class objects ... an object has a set of properties (fully dynamic), some of which may be functions, acting as the object's methods ... you may take the method of one object, and apply it to another instead (does not necessarily make sense, but it is feasible) ... any function may be used, to instantiate a new object ... and so on ... ECMA-Script does not have the concept of access levels, but you can hide away data using closures, if necessary ... ECMA-Script does not know classes ... but inheritance is achieved through its prototype based nature ...
i could go on ... but you see my point, i guess ... many languages implement only parts of all the things that most understand as OOP and emphasize different things ... sometimes it's a weakness, sometimes powerfull ... also the semantics, of what an object is, and what a method is, is VERY different ... to not confuse your students, you should really stick to one language, or languages having exactly the same semantics, when it comes to objects, and the describe what an object is ... otherwise, they will never actually understand you model ... once they got their head around it, you can show, how OOP looks in other languages ...
i think, you should take JavaScript or Ruby (although i think JavaScript is better, and then move on to ActionScript 2, to have a typed version of it, and classes, interfaces etc. ... or start with ActionScript 2 directly), to show concepts of OOP, since they are very radical, clear and simple ... or maybe other scripting languages ...
a thing not to forget is, that it's object oriented and not class oriented programming ... chosing a language, that does not need classes in order to have objects, seems a good idea ...
use a language, that is consistent and keeps code short and concise ... try to avoid situations, where you have n lines of code, that are mandatory, but you don't really have the time to explain them ...
in my opinion, introducing people to OOP first, is a good decision ... OOP is about modelling ... the higher the language, the more it teaches abstract thinking ... starting with procedural languages, where you maintain states in tons of variables scattered around your programm, is not good ... it takes a hell lot of time for people who really learned procedural programming, to move on to OOP ...
well, this was a little more, than i actually inteded to write ... hope it helps at least ... :)
greetz
back2dos