Nov 20, 2009

C# Tutorial : Lesson 4 - Object Oriented Programming

free web hosting
Open Discussion & Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > .NET (VB, C# & J#)

C# Tutorial : Lesson 4 - Object Oriented Programming

turbopowerdmaxsteel
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

 

 

 


Comment/Reply (w/o sign-up)

FeedBacker
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

Comment/Reply (w/o sign-up)

turbopowerdmaxsteel
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.

 

 

 


Comment/Reply (w/o sign-up)

(G)smsma
public data members
C# Tutorial : Lesson 4 - Object Oriented Programming

hey , I wondered about the declaration of public data members in the c# class.

why it is supposed for me to write public keyword before every data member that I want to be public ??! 

class student
{
    public string name;

    public string address;
    public int grade;
    public int age;

}

why not I write just one public keyword in the begin and all below data members become public such as in C++ ...!! 

Is there are any way to do that in c# I.E declaring many public data members with only one public keyword????

thanks alot

-question by smsma

Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : c, tutorial, lesson, 4, object, oriented, programming

  1. C# Tutorial : Lesson 9 - Constructors & Destructors
    (0)
  2. C# Tutorial : Lesson 8 - Functions/methods
    (0)
    The programming model has gone through many refinements, each change improving upon the model. One
    of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these
    are fragments of code within a program. They offer the following advantages:- Reduction of code
    duplication by offering re-usability Simplifying program logic by decomposing the program into
    smaller blocks Improving readability of the program Why do we need functions?
    Consider the following program:- CODE using System; namespace ConsoleApplication1 { ....
  3. C# Tutorial : Lesson 7 - Creating Value Types & Reference Types - Part II
    (2)
    foreach statement This statement is explicitly used to traverse through arrays. The
    benefit of using foreach over the normal for statement is that it is not needed to check the
    size of the array while using the former. Syntax:- foreach(type identifier in expression) {
    statement 1; statement 2; .... } Suppose we have an array StudentNames containing the name of all
    the students in a class. We need to display the name of each one of them on screen. First we will
    see how it can be done using the for loop. CODE string StudentNames = new string {"....
  4. C# Tutorial : Lesson 6 - Creating Value Types & Reference Types - Part I
    (0)
    Value Types & Reference Types In C#, Variables are either value types or reference types
    depending on what they store, values or references. By reference we imply that the variable holds
    the memory address of another location where the actual value is stored. All built in data types -
    Int, Char, String, Float, Boolean, etc are value types while classes are reference types. The
    following is a diagrammatic representation of these two types. In this picture there are two
    variables Num1 and Num2. Both of these being integer variables store the values directly.....
  5. C# Tutorial : Lesson 5 - Encapsulation & Abstraction
    (0)
    Encapsulation & Abstraction Two concepts that go together in the object oriented approach
    are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of
    an object, while Encapsulation is the hiding of the non-essential features. Think of a person
    driving a car. He does not need to know the internal working of the engine or the way gear changes
    work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much
    turning the steering wheel needs, etc (Abstraction). Consider the example from ....
  6. C# Tutorial : Lesson 3 - Programming Constructs
    (1)
    Conditional Branching By branching we imply, having different paths for execution.
    Conditions are used to determine which statements need to be executed. Suppose, you have a program
    to store the details of employees. Depending upon the post of the employee, there would be various
    fields associated with it. A department head, for example, would have a property denoting the
    department he heads, etc. We use conditional branching in such a scenario. C# provides the
    following conditional constructs:- if .. else Syntax:- if ( ) { statements } else { statement....
  7. C# Tutorial : Lesson 2 - Variables & Operators
    (0)
    Variables A Variable is a named location that stores a value. Although variables are
    physically stored in the RAM, their actual memory address is not known to the programmer. We can use
    the variables via the name we give them. These are the rules for naming a variable:- The name must
    begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9)
    or underscore (_) Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) { } , ; : . cannot be
    used in the variable name. A variable name must not be the same as a reserved k....
  8. C# Tutorial : Lesson 1 - Hello World Program
    (0)
    This is the first installment of my venture to explain the bits and pieces of C# that I have managed
    to learn at NIIT. In this lesson we would be creating the Hello World application. STEP 1 : Create
    a New Console Application in Visual C# The IDE automatically adds the following code:- CODE
    using System; using System.Collections.Generic; using System.Text; namespace HelloWorld {
        class Program     {         static void Main(string args)         {         }     } } Lets
    take a look at the first 3 lines. All of these lines begin with the keyword using....
  9. Lesson #3 - Basic Math Operators And Random #s
    Lesson #3 - Basic Math Operators and Random #s (0)
    In this lesson I will cover how to use basic math operations, well addition really but you can also
    use subtraction , division and multiplication . I would also like to note that when doing
    division, if variabes of int type are used you will not get any remainders (i.e. n.345984). To be
    able to work with real numbers, numbers with decimals, you can use float. Below is a way to declare
    a float and assign it a value: float floatNumber; float Number = 28.47f; Aside from
    generating random numbers and basic math operations, we will also incorporate an if statement a....
  10. Lesson #2 - Switch Statement In C#
    Using the Switch Statement in C# (3)
    In the previous lesson we demonstrated did a basic input output application which asked your your
    name and replied with a general greeting using the name you entered. In this lesson we are going
    to learn about a conditional statement called the switch statement. Usually if and if else
    statements are taught before switch statements. Although these are very useful, I find the switch
    to be easier and more fun to use. The program written below is very similar to the previous
    program where the user is asked to enter their name, however now the program will loo....
  11. Lesson #1 - Introduction To C#
    Console Application (1)
    This tutorial will help get you started with C# Sharp. These tutorials will assume that you are
    using the Visual Studio environment. If you are just curious to test out some code, then you can
    copy and paste this code into your CS file, however, before doing so, make sure to name your project
    the same as the namespace on the code. But since this first program is fairly easy, it will not
    hurt to type it out. It is fairly easy and short. Also, this program is highly commented so it
    should be easy to follow along. Comments will have 2 forward slashes before them '....

    1. Looking for c, tutorial, lesson, 4, object, oriented, programming

See Also,

*SIMILAR VIDEOS*
Searching Video's for c, tutorial, lesson, 4, object, oriented, programming
advertisement



C# Tutorial : Lesson 4 - Object Oriented Programming

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com