26 March 2012

Introduction to OOP #Part 3

In this part, I'll continue this post , so our class has started to have its own structure and to take his own form (mask) and it usable now, let's see our class:

class Person
{
  string FirstName {get; set;}
  string LastName {get; set;}


    void Sleep(int hours)
    {
     // body

    }
}


This class can be used in our first example with first and last names in more flexibility way, let's add one additional 'function', a function differs from a method while a method doesn't return any result of any dataType because it is marked with "void", the function returns any type of result (like 'int' in this example):



int CalculateAge(int BirthYear)

{
  return DateTime.Now.Year - BirthYear;
}



Our function does one simple operation, it return our age by passing just the year of birth, it does a simple calculation - the DateTime class comes from .Net classes and has also his own properties, methods and functions defined.

Modifiers - Before we can use our class we need to know about modifiers, modifiers are something like access point keys (or protection levels) of methods, properties, functions..etc. I'll for now just shortly explain two very common modifiers: "private" and "public", those two keywords are placed before the property, method, function..etc.. if it isn't added it is marked internally as "private", Let's see by just adding "private" keyword before the 'string':


private string myPrivateString = "hello";


With "private" keyword or modifier you can access for instance this variable only within the declaration scope, I'll write more about scopes and modifiers in coming posts.
With "public" keyword we can have access to the variable, method, function..etc. through our instance of the object, Let's see one example:

public string myPublicString = "hello there";



What's next?
Because of my time limit I'm not able to continue this post for now, maybe in the coming posts - and for next I'll try to cover more about classes and their common usages. Thanks for your time comments are welcome, you can also share this content or invite friends to follow my posts, feel free by providing ideas of getting better or asking questions.

No comments:

Post a Comment