One of the most common questions on Yahoo! Answers is how classes or objects, or the parts of a class / object, such as properties, methods and events, work.
Here’s a gross simplification of how classes and objects work. Most of this is lifted from a previous blog entry, Interpreting A C# Class Code Structure.
Classes / Objects
A class or object is a way of combining all sorts of data that relates to a single thing in one place, and a way of associating functions with that data. (For most intents and purposes, classes and objects are the same thing. Whenever I use the term class, I also mean object; whenever I use object, I also mean class. More on that in a moment.)
For example, you can think of a human as a class.
In the human class, you are an instance. For example, you might think that God decided to run this code when you were born:
Dim you As New HumanBeing()
What He did was create a variable, named you, and set the value of that variable to be an instance of the HumanBeing object. An instance is the actual use of an object. The object is the mold; the instance is the actual thing you made from the mold.
(Most programmers use the term class when they are speaking about an instance, and object when they are talking in general terms, so that’s the real difference between class and object. However, you can generally use the two terms interchangeably when discussing a specific programming issue.)
A property — often also called an attribute — is a bit of data that describes something about the object. For example, humans have certain properties — skin color, height, weight, age, etc.
Properties can be any kind of data — a string (such as your name); a number (such as your age); a date (such as your birthday); an array (such as a list of your siblings); even another class (such as a your car; it’s an entirely different thing that we would explain with a different class, but since you own it, it’s one of your properties).
Properties often can be changed, but sometimes cannot; sometimes, they exist only under certain circumstances, and sometimes, they once existed, but no longer do. For example, your weight can change easily, depending on your diet and exercise. Your race never changes. You won’t have children until you have sex; if you get divorced, you won’t have a spouse anymore.
For example, using our HumanBeing class, we might have the following properties:
Dim you As New HumanBeing() you.Name = "John Q. Public" you.Birthday = "2/15/1980"
And so on, and so forth. The .Name and .Birthday and the like are the properties for the HumanBeing class; we overload the = operator to assign the property.
Overloading means, in part, that we use something, such as an arithmetical operator (+, -, =, %, etc.), which normally is used to do something else, in order to do somethingin our class. In this case, we use the = sign not to get the result of a arithmetical expression; we use it to assign a value to a property. Other times, we might use a function name, such as Save() or Print(), which exists in lots of other classes under the same name, to do something in our class.
Dim you As New HumanBeing("John Q.Public", "2/15/1980")
Every class has a constructor. Constructors are a way to make sure a class has basic properties set when it is instantiated. In the code example above, our constructor would be accepting two attributes: Name and Birthday. The values we gave as arguments will be assigned to the correct properties by our constructor.
Some classes have constructors that require us to provide it with certain properties; other classes will allow us to instatiate the class without any default properties. Some classes have many, many constructors, so we can provide no initial properties, a few initial properties, or lots of initial properties, based on our whim. Some classes even require us to provide no properties whatsoever to the constructor. It all depends on how the class was made.
A method is a series of instructions we give a class, to make it create, change or remove properties; or, to provide us with some data based on its properties. Methods are basically functions that are tied to a class; they work with the data (properties) in the class, and their results affect only the data (properties) in the class.
For example, humans have ways of going about doing things or changing our properties: eating, sleeping, dieting, for example. Those would be considered methods of the HumanBeing class.
Let’s examine this code:
Dim you As New HumanBeing() you.Name = "John Q. Public" you.Weight = 200 'in pounds you.Eat(5000) 'method: argument is calories consumed Response.Write(you.Weight)
The Eat() method in this example takes an argument of the number of calories to consume. It could then simply divides that number by 2,000 — the number of calories you need to consume to gain a pound — and add the result onto the Weight property.
Thus, when we echo out the Weight property after running the Eat method through our class, it echoes back 202.5 — we find that you have gained 2.5 pounds! Let’s get rid of those extra pounds:
you.Exercise("Jai alai", 4) 'exercise type; hours of exercise Response.Write(you.Weight)
In this case, our Exercise() method will take two arguments: An exercise we’ll use and a length of time, in hours, we’ll do it.
We’ve specificed that we will do jai alai for four hours. At our weight, jai alai burns roughtly 1,035 calories per hour, so 1,035 * 4 = 4,140. Divide that by 2,000 and we get 2.07, which we’ll round up to 2.1. Therefore, when we echo out Weight again, we’ll get 200.4. You lost 2.1 pounds!
Methods don’t necessarily need to modify properties; they can, for example, simply report the value of a property, or somehow affect the class in other ways.
We might have a method for the HumanBeing class that we call IntroduceYourself(); all that method would do is echo out a string, “Hello, my name is ” + you.Name. Or, we might have a method called IgnoreSpouse(); all it would do is prevent you from accepting input from the instance of HumanBeing to which you are married.
An event is a trigger of some sort that tells a class to invoke a method or change a property. For example, humans get hungry, cold, sick, married, born, etc. All of these events either cause us to change a property (lose weight, become more happy, etc.) or invoke certain methods (eat, sleep, etc.).
For example, you might define hunger in a HumanBeing as a state when you use up more calories — Exercise() — than you take in — Eat(). That would then raise the event OnHungry.
We deal with events via handlers. A handler is a function or subroutine that is called (or raised) when a class has an event take place. To deal with our OnHungry event, we might call this subroutine (apologies to Rudolph The Red-Nosed Reindeer):
Sub EatPapaEat() Handles you.OnHungry Dim currentWeight As Single = you.Weight; Dim targetWeight As Single = 200; Do While (currentWeight < targetWeight) you.Eat(2000) ' take in 2000 calories until we are back up to 200 pounds currentWeight = you.Weight Loop End Sub
This handler simply tells us to keep eating 2,000 calories until our weight is greater than the target weight; as soon as that happens, we are no longer hungry, so we stop eating. (If only it was that easy!)
The last part of our discussion is namespaces. A namespace is a collection of classes (and, sometimes, other namespaces) that all relate to a common thing.
For example, the US government is very complex, but certain things about it are all in common and relate to one another. The executive, legislative and judicial branches all work in concert, and all as dictated by the Constitution.
So, to define those relationships, and help each branch better interact with other branches, as well as other types of government agencies / employees in the same branch, we would use namespaces.
For example, if we had a namespace called Government, it might contain the classes / objects / namespaces President, Congress, Supreme Court, Department of Justice, Social Security, etc.
If we had a namespace named Congress, we might employ it in a program by calling:
If we wanted the Senate namespace, we might call:
Within the Senate namespace, we might have the class Senator, with properties such as Name, State and Party; methods such as MakeSpeech, ShakeHands or KissBabies; and events such as OnBeingInterviewed, OnMakingSpeech or OnBeingIndicted.
You can also think of namespaces in terms of last names. (Though this analogy is quite stretched, it gives you a basic idea of how namespaces work.)
For example, if you are John Smith, your mom is Sally Smith and your uncle is Robert Smith, you could all be said to be in the namespace “Smith.”
To be able to talk about Robert, we might ask for the Smith.Uncle namespace; we now know we want to deal with the uncles in the Smith family.