Welcome Guest ( Log In | Register )



 
Reply to this topicStart new topic
> C# Tutorial : Lesson 4 - Object Oriented Programming
turbopowerdmaxst...
post Apr 4 2007, 08:26 AM
Post #1


Premium Member
Group Icon

Group: [HOSTED]
Posts: 410
Joined: 16-February 06
From: Kolkata, India
Member No.: 11,322
myCENTs:82.69



Object Oriented Programming

Object Oriented Programming is a methodology modeled on real life. It comprises of the basic unit, an object, being used in implementing a program. Think of all the objects around you - cars, buses, birds, trees, etc. You will find countless ones of them, everywhere you go. In order to tackle this huge number, we started classifying them, thus came the term Class.

Class
A class is a composition of the theoretic characteristics (attributes and properties) of an object and the things it can do - behaviors, methods and features. Take the Car as an example. Its characteristics can include speed, color, number of gears, etc and it exhibits behaviors such as accelerate, brake and gear-change.



Object
An object is an instance of a class. Consider the Car class above, the Aston Martin that was used in the movie - Die another Day is an object of the car class. One point to note is that each object has at least one attribute that makes it unique.



Message Passing
Objects do not exist in isolation. They interact with other objects. These interactions take place through messages. Message passing is the process by which an object (sender) sends data to another object (receiver) or asks the other object to invoke a method. Thus, each message has a sender and a receiver.

Behavior
It is how an object acts and reacts, in terms of its state changes and message passing. For example, when the driver applies the break, the car comes to a stop.



This was all about the object oriented methodology. Now, let us take a look on how OOP is used in C#

Declaring Classes
We declare classes using the following syntax:-

class < Class Name >
{

data members…

member functions…

}

Here class is a keyword. Class name can be anything that follows the naming rules.

Rules for naming classes
  • A class name must begin with a letter & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the class name.
  • A class name must not be the same as a reserved keyword such as using, public, etc.
Conventions for naming classes
  • Class Name must be meaningful, ideally a noun.
  • Naming of classes can be done using either the Pascal case, where the first character is capital and the rest are in small letters or using the Camel Case in which the first letter is in small case but the first letter of each successive word is in caps. Example:-
    • Pascal Case: Classone
    • Camel Case: classOne
The conventions are not mandatory but best practices, abiding by which allows others to easily understand our code.

Data members are the variables or other objects declared inside the class while member functions are the functions declared in it.

Example Class:-

CODE
class Student
{
    // Data Members
    public string Name;
    public int Age;

    // Member Function
    public void Display()
    {
        Console.WriteLine("Name {0}\n Age {1}", Name, Age);
    }
}


The public access specifier has been used in order to allow the data members & functions to be visible from outside the class. The access specifiers will be explained in the forthcoming tutorials.

Declaring & Instantiating Objects
Creating objects is similar to declaring variables and can be done using the syntax:-

<Class Name> <Object Name>;

Example: Student S1;

Before we start using the object, we need to instantiate it. Instantiation involves memory allocation and other basic initializations contained in the object’s constructor. We use the new keyword to instantiate objects. The syntax for which is given below:-

Note: Constructor is a special member function of a class that is used to initialize the data members. It will be dealt with, in later tutorials.

<Object Name> = new <Class Name>;

Example Usage: S1 = new Student();

These two steps can be done in a single line of code as Student S1 = new Student();

Using the Objects
We use the . (Dot) operator to access the members of the object. For example, to call the display method for the student class’s S1 object we write S1.Display();

Data members can be accessed in the similar fashion S1.Name = “Kenshin Himura”;

Releasing Memory
To release the memory occupied by the object we use S1 = null;

Example Program:-

CODE
using System;

namespace CSTutorials
{
    class Student
    {
        // Data Members
        public string Name;
        public int Age;

        // Member Function
        public void Display()
        {
            Console.WriteLine("Name {0}\n Age {1}", Name, Age);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student S1;             // Declaration
            S1 = new Student();     // Instantiation

            Student S2 = new Student();     // Single line Declaration & Instantiation

            // Assigning value to member variables
            S1.Name = "Michael";    
            S1.Age = 37;            

            S1.Name = "Kimi";
            S2.Age = 25;

            // Invoking member function
            S1.Display();          
            S2.Display();          
            Console.ReadLine();
        }
    }

}


Benefits of Object Oriented Programming
  • Realistic Modeling: Living in a ‘World of Objects’, the model built on real life is a much better approach because it allows issues to be tackled with greater accuracy.
  • Re-usability of code: Think of a scenario where a car making company specialized in two seaters decides to launch a four seater model. Converting the two seater model to a four seater is easier than designing a new model altogether.
  • Resilience to change: Being compartmentalized, individual objects can be improved without having to re-package the entire software.
  • Polymorphism: The behavior of an object can depend upon the state its in, thus exhibiting Polymorphism. Consider a car colliding with a wall. The impact of the process would depend upon the approach speed of the car, the Angle it strikes in, the strength of the wall and so on. If two cars were to collide, the results would be much different, with both of them receiving considerable damage.
Previous Tutorial - Lesson 3 - Programming Constructs

Next Tutorial - Lesson 5 - Encapsulation & Abstraction

Lesson: 1 2 3 4 5 6 7

This post has been edited by turbopowerdmaxsteel: Jun 9 2007, 04:11 AM
Go to the top of the page
 
+Quote Post
iGuest
post Mar 29 2008, 07:51 AM
Post #2


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



Access Specifier in C#
C# Tutorial : Lesson 4 - Object Oriented Programming

What are the access specifier in c#?

What was the main difference between Internal and protected access specifier?with example...

I need a brief explanation for Internal and protected access specifier?

-question by santhanalakshmi
Go to the top of the page
 
+Quote Post
turbopowerdmaxst...
post Mar 30 2008, 05:52 AM
Post #3


Premium Member
Group Icon

Group: [HOSTED]
Posts: 410
Joined: 16-February 06
From: Kolkata, India
Member No.: 11,322
myCENTs:82.69



There are four access specifiers in C#:
  • public
  • internal
  • protected
  • private

The above list is in the order of decreasing visibility. Members declared as public can be accessed from anywhere. The internal access specifier can be thought of as application public, i.e a member declared internal can be accessed from any other class belonging to the assembly. A protected member is public across the class hierarchy but private outside it. Protected members can be accessed in the child (derived classes). Those declared private can only be accessed inside the same class.

CODE
public class Base
{
    protected int Var1;
    internal int Var2;
}

public class Derived : Base
{
    public void MyMethod()
    {
        // Bot Members are inherited
        Var1 = "Value";
        Var2 = "Value";
    }
}

public class Unrelated
{
    public void MyMethod()
    {
        Base B = new Base();
        B.Var1 = "Value";    // Compile Error (Var1 cannot be accessed from this class)
        B.Var2 = "Value";
    }
}


The above code contains three classes: Base which declares two variables and is the base class for class Derived. A third class Unrelated exists in the same assembly. As you can see, Var1 and Var2 get inherited to the Derived class. As such, they are directly usable by a method of the class. Class Unrelated is not derived from class Base. It can however, access the members of class base by creating an object of it. internal members being public for the assembly are accessible through the Unrelated class. But, the protected variable Var1 is not accessible because Unrelated is not derived from class Base or any of its child classes.
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. Lesson #1 - Introduction To C#(1)
  2. Lesson #2 - Switch Statement In C#(1)
  3. C# Tutorial : Lesson 2 - Variables & Operators(0)
  4. C# Tutorial : Lesson 3 - Programming Constructs(1)
  5. C# Tutorial : Lesson 5 - Encapsulation & Abstraction(0)
  6. C# Tutorial : Lesson 6 - Creating Value Types & Reference Types - Part I(0)
  7. C# Tutorial : Lesson 7 - Creating Value Types & Reference Types - Part II(1)
  8. C# Tutorial : Lesson 8 - Functions/methods(0)
  9. C# Tutorial : Lesson 9 - Constructors & Destructors(0)


 



- Lo-Fi Version Time is now: 1st December 2008 - 07:07 PM