tags:

views:

205

answers:

8

I'm fairly new to programming, and there's one thing I'm confused by. What is a class, and how do I use one? I understand a little bit, but I can't seem to find a full answer.

By the way, if this is language-specific, then I'm programming in PHP.

Edit: There's something else I forgot to say. Specifically, I meant to ask how defining functions are used in classes. I've seen examples of PHP code where functions are defined inside classes, but I can't really understand why.

A: 

Here's a good page about Classes and Objects:

http://ficl.sourceforge.net/oo_in_c.html

Luca Matteis
+13  A: 

To be as succinct as possible: a class describes a collection of data that can perform actions on itself.

For example, you might have a class that represents an image. An object of this class would contain all of the data necessary to describe the image, and then would also contain methods like rotate, resize, crop, etc. It would also have methods that you could use to ask the object about its own properties, like getColorPalette, or getWidth. This as opposed to being able to directly access the color pallette or width in a raw (non-object) data collection - by having data access go through class methods, the object can enforce constraints that maintain consistency (e.g. you shouldn't be able to change the width variable without actually changing the image data to be that width).

This is how object-oriented programming differs from procedural programming. In procedural programming, you have data and you have functions. The functions act on data, but there's no "ownership" of the data, and no fundamental connection between the data and the functions which make use of it.

In object-oriented programming, you have objects which are data in combination with actions. Each type of data has a defined set of actions that it can perform on itself, and a defined set of properties that it allows functions and other objects to read and write in a defined, constraint-respecting manner.

The point is to decouple parts of the program from each other. With an Image class, you can be assured that all of the code that manipulates the image data is within the Image class's methods. You can be sure that no other code is going to be mucking about with the internals of your images in unexpected ways. On the other hand, code outside your image class can know that there is a defined way to manipulate images (resize, crop, rotate methods, etc), and not have to worry about exactly how the image data is stored, or how the image functions are implemented.

Edit: And one more thing that is sometimes hard to grasp is the relationship between the terms "class" and "object". A "class" is a description of how to create a particular type of "object". An Image class would describe what variables are necessary to store image data, and give the implementation code for all of the Image methods. An Image object, called an "instance" of an image class, is a particular use of that description to store some actual data. For example, if you have five images to represent, you would have five different image "objects", all of the same Image "class".

Tyler McHenry
Good answer, all that is missing are some references to books or articles in case the questioner wants to dive deeper into OOP.
RedFilter
+3  A: 

Classes is a term used in the object oriented programming (OOP) paradigm. They provide abstraction, modularity and much more to your code. OOP is not language specific, other examples of languages supporting it are C++ and Java.

I suggest youtube to get an understanding of the basics. For instance this video and other related lectures.

anderstornvig
+3  A: 

Since you are using PHP I'll use it in my code examples but most everything should apply. OOP treats everything as an object, which is a collection of methods (functions) and variables. In most languages objects are represented in code as classes. Take the following code:

class person
{
   $gender = null;
   $weight = null;
   $height = null;
   $age = null;
   $firstName = null;
   $lastName = null;
   function __CONSTRUCT($firstName, $lastName)
   {
      //__CONSTRUCT is a special method that is called when the class is initialized
      $this->firstName = $firstName;
      $this->lastName = $lastName;
   }
}

This is a valid (if not perfect) class when you use this code you'll first have to initailize an instance of the class which is like making of copy of it in a variable:

$steve = new person('Steve', 'Jobs');

Then when you want to change some property (not technicaly the correct word as there are no properties in PHP but just bear with me in this case I mean variable). We can access them like so:

$steve->age = 54;

<shameless plug> I just wrote a blog post introducing OOP with both C# and PHP check it out here: http://blog.mywebprogrammer.com </shameless plug>

Unkwntech
Humans are typically a great tool to demonstrate OOP. I generally bring in another mammal when I discuss extending classes. But that may be a step further than what the author of the question is interested in at the moment.
Jonathan Sampson
I prefer vehicles myself, class vehicle{...} class truck extends vehicle{...} class car extends vehicles{...} and this is what I used on my blog
Unkwntech
+2  A: 

Note: this assumes you are a little familiar with programming, which I guess you are.

A class is like a blueprint. Let's suppose you're making a game with houses in it. You'd have a "House" class. This class describes the house and says what can it do and what can be done to it. You can have attributes, like height, width, number of rooms, city where it is located, etc. You can also have "methods" (fancy name for functions inside a class). For example, you can have a "Clean()" method, which would tell all the people inside the house to clean it.

Now suppose someone is playing your game and clicks the "make new house" button. You would then create a new object from that class. In PHP, you'd write "$house = new House;", and now $house has all the attributes and methods of a class.

You can make as many houses as you want, and they will all have the same properties, which you can then change. For example, if the people living in a house decide to add one more room, you could write "$house->numberOfRooms++;". If the default number of rooms for a house was 4, this house would have 5 rooms, and all the others would have 4. As you can see, the attributes are independent from one instance to another.

This is the basics; there is a lot more stuff about classes, like inheritance, access modifiers, etc.

Now, you may ask yourself why is this useful. Well, the point of Object Oriented Programming (OOP) is to think of all the things in the program as independent objects, trying to design them so they can be used regardless of context. For example, your house may be a standalone variable, may be inside an array of houses. If you have a "Person" class with a "residence" attribute, then your house may be that attribute.

This is the theory behind classes and objects. I suggest you look around for examples of code. If you want, you can look at the classes I made for a Pong game I programmed. It's written in Python and may use some stuff you don't understand, but you will get the basic idea. The classes are here.

Javier Badia
A: 

hi there,

This is a resource which I would kindly recommend http://www.cplusplus.com/doc/tutorial/

not sure why, but starting with C++ to apply OOP might be natural prior of any other language, the above link helped me a lot when I started at least.

Tiberiu Hajas
A: 

Classes are a way programmers mark their territory on code.
They are supposedly necessary for writing big projects.
Linus and his team must have missed that memo developing the linux kernel.

However, they can be good for organization and categorizing code I guess. It makes it easier to navigate code in an ide such as visual studio with the object browsers.

Here are some usage demonstrations of classes in 31 languages on rosettacode

Naveen
+1  A: 

A class is essentially an abstraction.

You have built-in datatypes such as "int" or "string" or "float", each of which have certain behavior, and operations that are possible.

For example, you can take the square root of a float, but not of a string. You can concatenate two strings, or you can add two integers. Each of these data types represent a general concept (integers, text or numbers with a fixed number of significant digits, which may or may not be fractional)

A class is simply a user-defined datatype that can represent some other concept, including the operations that are legal on it.

For example, we could define a "password" class which implements the behavior expected of a password. That is, we should be able to take a text string and create a password from it. (If I type 'secret02', that is a legal password). It should probably perform some verification on this input string, making sure that it is at least N characters long, and perhaps that it is not a dictionary word. And it should not allow us to read the password. (A password is usually represented as ****** on the screen). Instead, it should simply allow us to compare the password to other passwords, to see if it is identical.

If the password I just typed is the same as the one I originally signed up with, I should be allowed to log in. But what the password actually is, is not something the application I'm logging in to should know. So our password class should define a comparison function, but not a "display" function.

A class basically holds some data, and defines which operations are legal on that data. It creates an abstraction.

In the password example, the data is obviously just a text string internally, but the class allows only a few operations on this data. It prevents us from using the password as a string, and instead only allows the specific operations that would make sense for a password.

In most languages, the members of a class can be either private or public. Anything that is private can only be accessed by other members of the class. That is how we would implement the string stored inside the password class. It is private, so it is still visible to the operations we define in the class, but code outside the class can not just access the string inside a password. They can only access the public members of the class.

jalf