MSSql MySql Python javascript PHP java DotNet Ruby Hackme Takeawy Code Twitter Facebook

The house of developers, A website to classify and rank developers

 
 
 
 
Country Rank: 3
World Rank: 86
Profile Viewed: 203
Points: 4303
04 May 2010

Moving into OOP (Beginner's look at Classes/Objects)

Understanding Classes/Objects: The Basics.

The easiest way to think of a Class is a blue-print of what data will be related and specifications on how to use this data.  If we think of a class as a table in excel (or access), then we have our columns (which would each have it's own field name and data type), and we have our rows (or records) which represent each individual instance of the class (also known as an object).  So let's say for example, we have a very simple class with only one field and one property:

class Employee

{

   private string _id;

   public string ID

   {

      get { return _id;}

      set {_id= value;}

   }

}

Now, to take our blueprint and build a house, we would use this statement in the code that we wish to use our newly defined class:

Employee davidMcKenzie = new Employee();

davidjMcKenzie.id = "9999"; //This one will generate an error!!

davidjMcKenzie.ID = "9999"; //This works!!

In a table, this may look like:

Name(of instance)     _id (private)      ID(get)                  ID(set)

davidMcKenzie           9999               get value in _id       put value in _id

 

 

The reason that we use the getters/setters rather than the fields themselves, is because it is more secure than setting/getting the values directly from the fields.  Data within the fields cannot be accessed or changed from anywhere other than the get/set defined in the field’s public property.  This maintains ‘data hiding’ – which is one of the great features of Object-Oriented Programming.

When the program comes upon a property (davidMcKenzie.Id), it looks for an assignment operator.  If we specify one, then the program uses the ‘set’ method from within the property.  If the assignment operator is not there, then the program knows to use the ‘get’ method from within the property to return the value that is in that we specify.

That's it for now, but if you have questions, or need clarification, please feel free to ask.

Facebook Share Delicious Share Digg Share Google Buzz Share My Space Share Reddit Share Stumbleupon Share Technorati Share Twitter Share

Comments

Please, login or register to add a comment.