C# Tutorial : Lesson 04 – Object Oriented Programming

Partho Sarathi

21 Mar, 2009 · 5 minutes read

  • Share:
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 classis 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:-

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 publicaccess 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:-

;

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

= new ;

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:-

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;

			S2.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 seater’s 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.
  • Share:

The cleanest blogging platform


2024 © Maxotek. All rights reserved.