Developer Drain Brain

October 23, 2015

OOP 101 – Classes, Instances and Objects

Filed under: Development — rcomian @ 3:10 pm

For me, the most basic thing to understand when dealing with any kind of object oriented language is the relationship between classes and objects.

Lets go through the mechanics of what’s going on from a developer’s point of view.

If you’ve written any applications in java or C# you’ve certainly written some code that looks like this:

class MyClass()
  string MyMethod() {
    return "My string";

It doesn’t really matter what language you’re talking about here, the idea is the same in c++, java and c#. The exact syntax will vary, so don’t try to compile that code, but the overall idea is the same.

What we’ve done is define a class called MyClass. It contains a single method called MyMethod and that method just returns the string value "My string".

It’s worth knowing that on it’s own, writing, compiling and running that code won’t actually do anything at all. Not a thing. We’ve just set some stuff up.

To get it to do something you’ll need to instantiate that class. You will probably also have written something along the lines of this:

MyClass myObject = new MyClass();

Now we’ve done something a little more, we’ve taken the class we created before (MyClass) and created an object which is an instance of that class. We can refer to that object using the name myObject.
An object is an actual thing that lives in memory, it can have data associated with it and have a set of methods on it which we can call. Because that data and those methods are defined by a class, we call that object an instance of that class.
myObject is an instance of MyClass, so we have access to all the things that MyClass contained. That is, a class is just a definition, an object is a thing we can actually do things with.

So what can we do with an instance of MyClass? Because MyClass contains one method: MyMethod, we can call it:

MyClass myObject = new MyClass();
string returnedString = myObject.MyMethod();

This code creates an instance of MyClass, just like before, then calls the MyMethod method on that instance.
This method returns the string "My string", which itself gets stored in the string variable returnedString, which we can then use for other things.
So this code doesn’t do much, but serves as a starting point for understanding the difference between a class and an object.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: