Wednesday, March 25, 2015

Introduction to Object Oriented Programming Concepts in C#

Introduction to Object Oriented Programming (OOP) concepts in C#: Abstraction, Encapsulation, Inheritance and Polymorphism.
OOP Features 
Object Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic. 

OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects.
  1. The software is divided into a number of small units called objects. The data and functions are built around these objects.
  2. The data of the objects can be accessed only by the functions associated with that object.
  3. The functions of one object can access the functions of another object.
OOP has the following important features.

 Class
A class is the core of any modern Object Oriented Programming language such as C#.
In OOP languages it is mandatory to create a class for representing data. 
A class is a blueprint of an object that contains variables for storing data and functions to perform operations on the data. 
A class will not occupy any memory space and hence it is only a logical representation of data.
To create a class, you simply use the keyword "class" followed by the class name:
class Employee
{
 
}
 
Object
Objects are the basic run-time entities of an object oriented system. They may represent a person, a place or any item that the program must handle. 

"An object is a software bundle of related variable and methods."
 
"An object is an instance of a class"
oops-in-csharp.jpg  
A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object. 
When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance and its starting address will be stored in the object in stack memory.
When an object is created without the new operator, memory will not be allocated in the heap, in other words an instance will not be created and the object in the stack contains the value null.
When an object contains null, then it is not possible to access the members of the class using that object.
 
class Employee
{
 
}
Syntax to create an object of class Employee:
 
Employee objEmp = new Employee();
 
All the programming languages supporting Object Oriented Programming will be supporting these three main concepts:
  1. Encapsulation
  2. Inheritance
  3. Polymorphism
Abstraction
Abstraction is "To represent the essential feature without representing the background details."
 
Abstraction lets you focus on what the object does instead of how it does it.
 
Abstraction provides you a generalized view of your classes or objects by providing relevant information.
 
Abstraction is the process of hiding the working style of an object, and showing the information of an object in an understandable manner.
 
Real-world Example of Abstraction
Suppose you have an object Mobile Phone.
 
Suppose you have 3 mobile phones as in the following: 
 
Nokia 1400 (Features: Calling, SMS)
Nokia 2700 (Features: Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails)
 
Abstract information (necessary and common information) for the object "Mobile Phone" is that it makes a call to any number and can send SMS.
 
So that, for a mobile phone object you will have the abstract class as in the following:
   abstract class MobilePhone
    {
        public void Calling();
        public void SendSMS();
    }

    public class Nokia1400 : MobilePhone
    {
    }

    public class Nokia2700 : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
    }

    public class BlackBerry : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
        public void Recording();
        public void ReadAndSendEmails();
    }
 
Abstraction means putting all the variables and methods in a class that are necessary.
For example: Abstract class and abstract method.
Abstraction is a common thing.
Example
If somebody in your collage tells you to fill in an application form, you will provide your details, like name, address, date of birth, which semester, percentage you have etcetera.
If some doctor gives you an application to fill in the details, you will provide the details, like name, address, date of birth, blood group, height and weight.
See in the preceding example what is in common?
Age, name and address, so you can create a class that consists of the common data. That is called an abstract class. 
That class is not complete and it can be inherited by other classes.
 
Encapsulation
Wrapping up a data member and a method together into a single unit (in other words class) is called Encapsulation.
 
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.
 
Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the property of encapsulating members and functions.
 
    class Bag
    {
        book;
        pen;
        ReadBook();
    }
 
Encapsulation means hiding the internal details of an object, in other words how an object does something.
 
Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.
 
Encapsulation is a technique used to protect the information in an object from another object.
 
Hide the data for security such as making the variables private, and expose the property to access the private data that will be public.
So, when you access the property you can validate the data and set it.
 
Example 1
    class Demo
    {
        private int _mark;

        public int Mark
        {
            get { return _mark; }
            set { if (_mark > 0) _mark = valueelse _mark = 0; }
        }
    }
 
Real-world Example of Encapsulation
Let's use as an example Mobile Phones and Mobile Phone Manufacturers.
Suppose you are a Mobile Phone Manufacturer and you have designed and developed a Mobile Phone design (a class). Now by using machinery you are manufacturing Mobile Phones (objects) for selling, when you sell your Mobile Phone the user only learns how to use the Mobile Phone but not how the Mobile Phone works.
 
This means that you are creating the class with functions and by with objects (capsules) of which you are making available the functionality of your class by that object and without the interference in the original class.
 
Example 2
TV operation 
It is encapsulated with a cover and we can operate it with a remote and there is no need to open the TV to change the channel. 
Here everything is private except the remote, so that anyone can access the remote to operate and change the things in the TV.
 
Inheritance
When a class includes a property of another class it is known as inheritance.
Inheritance is a process of object reusability.
For example, a child includes  the properties of its parents.
    public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine("Parent Constructor.");
        }

        public void print()
        {
            Console.WriteLine("I'm a Parent Class.");
        }
    }

    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("Child Constructor.");
        }

        public static void Main()
        {
            ChildClass child = new ChildClass();

            child.print();
        }
    }
 
Output
    Parent Constructor.
    Child Constructor.
    I'm a Parent Class.
 
Polymorphism
Polymorphism means one name, many forms.
One function behaves in different forms.
In other words, "Many forms of a single object is called Polymorphism."
 
Real-world Example of Polymorphism
Example 1
A teacher behaves students.
A teacher behaves his/her seniors.
Here teacher is an object but the attitude is different in different situations.
Example 2
A person behaves the son in a house at the same time that the person behaves an employee in an office.
Example 3
Your mobile phone, one name but many forms:
  • As phone
  • As camera
  • As mp3 player
  • As radio
To read about Polmorphism in detail click the following link:

Polymorphism in .Net 
 
The Differences between Abstraction and Encapsulation
AbstractionEncapsulation
1.  Abstraction solves the problem at the design level.1. Encapsulation solves the problem in the implementation level.
2. Abstraction hides unwanted data and provides relevant data.2. Encapsulation means hiding the code and data into a single unit to protect the data from the outside world.
3. Abstraction lets you focus on what the object does instead of how it does it3. Encapsulation means hiding the internal details or mechanics of how an object does something.
4. Abstraction: Outer layout, used in terms of design.
For example:
An external of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.
 
4. Encapsulation- Inner layout, used in terms of implementation.
For example: the internal details of a Mobile Phone, how the keypad button and display screen are connected with each other using circuits.
 The easier way to understand abstraction and encapsulation is as follows.
Real-world Example
Use an example of a Mobile Phone
You have a Mobile Phone, you can dial a number using keypad buttons. You don't even know how these are working internally. This is called Abstraction. You only have the information that is necessary to dial a number. But not internal working of the mobile.
 
But how does the Mobile Phone work internally? How are the keypad buttons connected with internal circuit? That is called Encapsulation.
Summary
"Encapsulation is accomplished using classes. Keeping data and methods that access that data into a single unit." 
"Abstraction is accomplished using an Interface. Just giving the abstract information about what it can do without specifying the details."
"Information/Data hiding is accomplished using modifiers by keeping the instance variables private or protected."




Class
A class is basically a combination of a set of rules on which we will work in a specific program. It contains definitions of new data types like fields or variables, operations that we will perform on data (methods) and access rules for that data.

Example
Class Example
{
    /* fields,
    Variables,
    Methods,
    Properties,
    */
}

Object
Objects are defined as an instance of a class. Objects are built on the model defined by the class. An object can be created in memory using the "new" keyword. In C# objects are reference types and other data type variables are value types. In C# objects are stored in the heap while other value types are stored in the stack.

Example
Example exmplObject = new Example();

Inheritance
Inheritance is relevant due to the concept of “Code Reusability”. Inheritance is a feature by which a class acquires attributes of another class. The class that provides its attributes is known as the base class and the class that accepts those attributes is known as a derived class. It allows programmers to enhance their class without reconstructing it.

Example
 
class BaseClass
{
}
class DerivedClass : BaseClass
{
}

Now an object of a derived class can use the accessible properties of the base class without defining it in the derived class.

Encapsulation
Encapsulation is defined as hiding irrelevant data from the user. A class may contain much information that is not useful for an outside class or interface. The idea behind this concept is “Don’t tell me how you do it. Just do it.”.

So classes use encapsulation to hide its members that are not relevant for an outside class or interface. Encapsulation can be done using access specifiers.

Abstraction
Abstraction is defined as showing only the relevant data to the user. Generally abstraction and encapsulation are explained in confusing manners.

Example
So just take an example of Mobile Phone Design.
Relevant Features of a phone in which the user is interested are Camera, Music player, Calling function, Voice recording and so on.

Irrelevant Features of a phone in which the user is not interested are circuit board design, hardware used and so on.

So in designing the Mobile Phone Model, both relevant and irrelevant features are required. But we need to show only relevant features. So we design a Mobile Phone in such a way that only relevant features are shown and irrelevant features are hidden. And remember one thing, that deciding relevant and irrelevant features is totally a user choice.

Polymorphism
Polymorphism is defined as the implementation of the same method with different attributes in a different context.

Example
For example, we have a class named shape with a method name buildshape(). We need to use it in the class Circle, class triangle and the class quadrilateral. So for every class we use the buildshape() method but with different attributes.

Introduction

In this article, I want to show you the concept of Object-Oriented Programming in C#. Now what are objects and why we’d better write Object-Oriented applications? Good Question! We will cover the following:
  • What is an object?
  • Creating a class
  • Fields
  • Methods
  • Instantiating your class
  • Access Modifiers
  • Properties

What is an Object

In order to understand the meaning of object in our context, you should first understand the concept of classes. Everything in C# .NET is a class. From integer data type to complex encryption and ADO.NET classes. So, for example, when you write the following code, you are actually using FileStream class to declare a variable name fileStream.
FileStream fileStream = new FileStream(fileName, FileMode.Create)); 
So, as you can see, fileStream is a variable of type FileStream which is a class. We call fileStream an object or an instance of type FileStream class rather than a variable because everything is considered as an object. I hope I have made myself clear so far. So, keep in mind that every instance of a class is called an object.
So far we have seen what the difference between a class and an object is. The following is Microsoft’s definition of these terms:
A class definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances.
Every instance of a particular class can access some properties and methods of that class. For example, considering fileStream as an object of type FileStream class, we could write:
byte[] dataArray = new byte[100000];
for(int i = 0; i < dataArray.Length; i++)
     {
         fileStream.WriteByte(dataArray[i]);
     }
fileStream is calling WriteByte which is a method declared in FileStream class and what it does is not of any interest to us right now. We can also access the properties that are allowed via our instance of a class. Again, assuming fileStream to be an instance of FileStream class, we could write:
if (fileStream.CanWrite)
            {
                Console.WriteLine("The stream for file is writable.")
            }
            else
            {
                Console.WriteLine("The stream for file is not writable.");
            }
I think you have got the idea of classes and objects. However, this was the beginning. I don’t want to go through the classes provided by Microsoft and guide you how to use them but rather I want to show you how you can declare classes of your own. The classes that you create can have methods and properties similarly to those already in the .NET and you can set access policies to those methods and properties which we call members from now on.

Creating a Class

To create a class, you need to add a class file to your project. Right-click on your project inside the solution explorer and click Add and then choose New Item…. On the left side of the new window, navigate to Code template and then click Class from the right-sided pane. Choose a name for your class and click Add. A new file is added to your project. Inside it, you see the declaration of your class as follows. I have named my class Car and it is in the OOPLearning namespace:
namespace OOPLearning
{
    class Car
    {
    }
}

Fields

To add a field (and a field is simply an object within your class, it could by an integer or any other object) just write the data type of the field and the name:
int numberOfDoors; 
In the above line of code, I have declared a field of type int which stores the number of the doors that an instance of this class has.

Methods

Methods are the behaviors of your class; the things that an object of that class can do. For example, a class named Dog may have a method named Bark, as dogs bark. And a class named Car can have a method namedAccelerate, as cars can accelerate.
We add a method to our class in this manner:
void Accelerate()
{
    //The logic goes here
}
I have eliminated the logic for this method because it’s not of any interest to us right now.

Instantiating your Class

Instantiating (creating an instance of a class) is simply the process of declaring an object of a class. You can instantiate a class as follows (I have created a console application and declared an object of type Car in theMain method of the Program.cs file of my project):
namespace OOPLearning
{
    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car ();
        }
    }
}

Access Modifiers

As I said, when you create an instance of a class, you can access the members (methods and fields) of that class via your instance. So, this means that I could write the following:
Car myCar = new Car ();
myCar.numberOfDoors=4;
myCar.Accelerate ();
But as you see, the above code has generated an error. Why is that? Because we don’t have access to these members and this is due to their access modifiers which are private. The private keyword is not explicitly written before the Accelerate and numberOfDoors. But since it’s the default access modifier, anything (either method, fields, etc.) that you declare in your class is considered private unless you write one of the following before them:
  • public
  • protected
  • internal
  • internal protected
We don’t go through these keywords right now. Let’s just change the definition of our class as follows:
namespace OOPLearning
{
    class Car
    {
        public int numberOfDoors;

        public void Accelerate()
        {
            //The logic goes here
        }
    }
}
Now, you can instantiate the Car class and access numberOfDoors and Accelerate:
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.numberOfDoors=4;
        Console.WriteLine (myCar.numberOfDoors);
        myCar.Accelerate ();
    }
}
Notice that I have set numberOfDoors to the value and then print it out on the console. Simple as that.

Properties

Remember I said fields act as stores for your data. The numberOfDoors is the storage in which we store the number of doors our myCar object has. What if we wanted to control the value passed to this field. For example, the following code would be perfectly valid:
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.numberOfDoors=250;
        Console.WriteLine (myCar.numberOfDoors);
    }
}
But we know that there is no car in the whole world which has 250 doors. We want to make sure the value passed to numberOfDoors is intellectually acceptable. So, we use properties. A property is simply a method that which can help us add logic to when the value of a field is retrieved or set. Look at the following line of code:
private int numberOfDoors;

public int NumberOfDoors
{
    get { return numberOfDoors; }
    set
    {
        if ( value >= 2 && value <= 6 )
        {
            numberOfDoors = value;
        }
    }
As it’s obvious, we control the value passed to the numberOfDoors and only accept it if it’s between and 6. Now, the property named NumberOfDoors is actually a method which has two parts: getset. The get part is called whenever we retrieve the value stored in nubmerOfDoors and the set part is called whenever we pass a value to be stored in numberOfDoors. Notice the data type of the property and the field match. Also, pay attention to the syntax. Now, if we write the following code, we see the value in the console as the default value of type integer is:
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car ();
        myCar.NumberOfDoors=250;
        Console.WriteLine (myCar.NumberOfDoors);
        Console.ReadKey ();
    }
}
What happened is simply logical. Since the value passed to NumberOfDoors doesn’t conform to our rules (between and 8) the default value of type integer which is zero (which is stored in the field numberOfDoors) is returned. To better understand the concept, let’s change our class to look like this:
private int numberOfDoors;

get { return numberOfDoors; }
set
{
    if ( value >= 2 && value <= 6 )
    {
        numberOfDoors = value;
    }
    else
    {
        numberOfDoors = 2;
    }
}
Now run the project again. You see in the console. And that’s because of the else in the set part ofNumberOfDoors. If the value passed to the property conforms to our rule, then everything is quite good, otherwise it is set to value 2. There is a lot to properties, but we close our discussion on them here.


Object-oriented programming

In this part of the C# tutorial, we will talk about object oriented programming in C#.
There are three widely used programming paradigms: procedural programming, functional programming and object-oriented programming. C# supports both procedural and object-oriented programming.
Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs.
There are some basic programming concepts in OOP:
  • Abstraction
  • Polymorphism
  • Encapsulation
  • Inheritance
The abstraction is simplifying complex reality by modeling classes appropriate to the problem. The polymorphism is the process of using an operator or function in different ways for different data input. The encapsulation hides the implementation details of a class from other objects. Theinheritance is a way to form new classes using classes that have already been defined.

Objects

Objects are basic building blocks of a C# OOP program. An object is a combination of data and methods. The data and the methods are called members of an object. In an OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages and process data.
There are two steps in creating an object. First, we define a class. A class is a template for an object. It is a blueprint which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.
using System;

public class Being {}

public class Objects
{
    static void Main()
    {
        Being b = new Being();
        Console.WriteLine(b);
    }
}
In our first example, we create a simple object.
public class Being {}
This is a simple class definition. The body of the template is empty. It does not have any data or methods.
Being b = new Being();
We create a new instance of the Being class. For this we have the new keyword. The b variable is the handle to the created object.
Console.WriteLine(b);
We print the object to the console to get some basic description of the object. What does it mean, to print an object? When we print an object, we in fact call its ToString() method. But we have not defined any method yet. It is because every object created inherits from the base object. It has some elementary functionality which is shared among all objects created. One of this is theToString() method.
$ ./simpleobject.exe 
Being
We get the object class name.

Object attributes

Object attributes is the data bundled in an instance of a class. The object attributes are calledinstance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy.
using System;

public class Person 
{
    public string name;
}

public class ObjectAttributes
{
    static void Main()
    {
        Person p1 = new Person();
        p1.name = "Jane";

        Person p2 = new Person();
        p2.name = "Beky";

        Console.WriteLine(p1.name);
        Console.WriteLine(p2.name);
    }
}
In the above C# code, we have a Person class with one member field.
public class Person 
{
    public string name;
}
We declare a name member field. The public keyword specifies that the member field will be accessible outside the class block.
Person p1 = new Person();
p1.name = "Jane";
We create an instance of the Person class and set the name variable to "Jane". We use the dot operator to access the attributes of objects.
Person p2 = new Person();
p2.name = "Beky";
We create another instance of the Person class. Here we set the variable to "Beky".
Console.WriteLine(p1.name);
Console.WriteLine(p2.name);
We print the contents of the variables to the console.
$ ./person.exe 
Jane
Beky
We see the output of the program. Each instance of the Person class has a separate copy of the name member field.

Methods

Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods bring modularity to our programs.
Methods are essential in the encapsulation concept of the OOP paradigm. For example, we might have a Connect() method in our AccessDatabase class. We need not to be informed how exactly the method Connect() connects to the database. We only have to know that it is used to connect to a database. This is essential in dividing responsibilities in programming, especially in large applications.
Objects group state and behavior, methods represent the behavioral part of the objects.
using System;

public class Circle 
{
    private int radius; 

    public void SetRadius(int radius)
    {
        this.radius = radius;
    }

    public double Area()
    {
        return this.radius * this.radius * Math.PI;
    }
}

public class Methods
{
    static void Main()
    {
        Circle c = new Circle();
        c.SetRadius(5);

        Console.WriteLine(c.Area());
    }
}
In the code example, we have a Circle class. We define two methods.
private int radius;
We have one member field. It is the radius of the circle. The private keyword is an access specifier. It tells that the variable is restricted to the outside world. If we want to modify this variable from the outside, we must use the publicly available SetRadius() method. This way we protect our data.
public void SetRadius(int radius)
{
    this.radius = radius;
}
This is the SetRadius() method. The this variable is a special variable which we use to access the member fields from methods. The this.radius is an instance variable, while the radius is a local variable, valid only inside the SetRadius() method.
Circle c = new Circle();
c.SetRadius(5);
We create an instance of the Circle class and set its radius by calling the SetRadius() method on the object of the circle. We use the dot operator to call the method.
public double Area()
{
    return this.radius * this.radius * Math.PI;
}
The Area() method returns the area of a circle. The Math.PI is a built-in constant.
$ ./circle.exe 
78.5398163397448
Running the example gives this outcome.

Access modifiers

Access modifiers set the visibility of methods and member fields. C# has four access modifiers:publicprotectedprivate and internal. The public members can be accessed from anywhere. Theprotected members can be accessed only within the class itself and by inherited and parent classes. The private members are limited to the containing type, e.g. only within its class or interface. The internal members may be accessed from within the same assembly (exe or DLL).
Access modifiers protect data against accidental modifications. They make the programs more robust.
using System;

public class Person 
{
    public string name;
    private int age;

    public int GetAge()
    {
        return this.age;
    }

    public void SetAge(int age)
    {
        this.age = age;
    }
}

public class AccessModifiers
{
    static void Main()
    {
        Person p = new Person();
        p.name = "Jane";
 
        p.SetAge(17);

        Console.WriteLine("{0} is {1} years old", 
            p.name, p.GetAge());
    }
}
In the above program, we have two member fields. One is declared public, the other private.
public int GetAge()
{
    return this.age;
}
If a member field is private, the only way to access it is via methods. If we want to modify an attribute outside the class, the method must be declared public. This is an important aspect of data protection.
public void SetAge(int age)
{
    this.age = age;
}
The SetAge() method enables us to change the private age variable from outside of the class definition.
Person p = new Person();
p.name = "Jane";
We create a new instance of the Person class. Because the name attribute is public, we can access it directly. However, this is not recommended.
p.SetAge(17);
The SetAge() method modifies the age member field. It cannot be accessed or modified directly because it is declared private.
Console.WriteLine("{0} is {1} years old", 
    p.name, p.GetAge());
Finally, we access both members to build a string.
$ ./modifiers.exe 
Jane is 17 years old
Running the example gives this output.
Member fields with private access modifiers are not inherited by derived classes.
using System;

public class Base 
{
    public string name = "Base";
    protected int id = 5323;
    private bool isDefined = true;
}

public class Derived : Base 
{
    public void info()
    {
        Console.WriteLine("This is Derived class");
        Console.WriteLine("Members inherited");
        Console.WriteLine(this.name);
        Console.WriteLine(this.id);
        // Console.WriteLine(this.isDefined);
    }
}

public class CSharpApp
{
    static void Main()
    {
        Derived drv = new Derived();
        drv.info();
    }
}
In the preceding program, we have a Derived class which inherits from the Base class. The Baseclass has three member fields. All with different access modifiers. The isDefined member is not inherited. The private modifier prevents this.
public class Derived : Base 
The class Derived inherits from the Base class. To inherit from another class, we use the colon (:) operator.
Console.WriteLine(this.name);
Console.WriteLine(this.id);
// Console.WriteLine(this.isDefined);
The public and the protected members are inherited by the Derived class. They can be accessed. The private member is not inherited. The line accessing the member field is commented. If we uncommented the line, the code would not compile.
$ ./protected.exe 
This is Derived class
Members inherited
Base
5323
Running the program, we receive this output.

The constructor

A constructor is a special kind of a method. It is automatically called when the object is created. Constructors do not return values. The purpose of the constructor is to initiate the state of an object. Constructors have the same name as the class. The constructors are methods, so they can be overloaded too.
Constructors cannot be inherited. They are called in the order of inheritance. If we do not write any constructor for a class, C# provides an implicit default constructor. If we provide any kind of a constructor, then a default is not supplied.
using System;

public class Being 
{
    public Being() 
    {
        Console.WriteLine("Being is created");
    } 

    public Being(string being)
    {
        Console.WriteLine("Being {0} is created", being);

    }
}

public class Constructor
{
    static void Main()
    {
        new Being();
        new Being("Tom");
    }
}
We have a Being class. This class has two constructors. The first one does not take parameters; the second one takes one parameter.
public Being(string being)
{
    Console.WriteLine("Being {0} is created", being);
}
This constructor takes one string parameter.
new Being();
An instance of the Being class is created. This time the constructor without a parameter is called upon object creation.
$ ./constructor.exe 
Being is created
Being Tom is created
This is the output of the program.
In the next example, we initiate data members of the class. Initiation of variables is a typical job for constructors.
using System;

public class MyFriend 
{
    private DateTime born;
    private string name;
   
    public MyFriend(string name, DateTime born)
    {
        this.name = name;
        this.born = born;
    }

    public void Info() 
    {
        Console.WriteLine("{0} was born on {1}",
            this.name, this.born.ToShortDateString());
    } 
}

public class Constructor2
{
    static void Main()
    {
        string name = "Lenka";
        DateTime born = new DateTime(1990, 3, 5);

        MyFriend fr = new MyFriend(name, born);
        fr.Info();
    }
}
We have a MyFriend class with data members and methods.
private DateTime born;
private string name;
We have two private variables in the class definition.
public MyFriend(string name, DateTime born)
{
    this.name = name;
    this.born = born;
}
In the constructor, we initiate the two data members. The this variable is a handler used to reference the object variables.
MyFriend fr = new MyFriend(name, born);
fr.Info();
We create a MyFriend object with two arguments. Then we call the Info() method of the object.
$ ./constructor2.exe 
Lenka was born on 3/5/1990
We execute the constructor2.exe program.

Constructor chaining

Constructor chaining is the ability of a class to call another constructor from a constructor. To call another constructor from the same class, we use the this keyword.
using System;

public class Circle 
{
    public Circle(int radius)
    {
        Console.WriteLine("Circle, r={0} is created", radius);
    }

    public Circle() : this(1) 
    {

    }
}

public class ConstructorChaining
{
    static void Main()
    {
        new Circle(5);
        new Circle();
    }
}
We have a Circle class. The class has two constructors. One that takes one parameter and one that does not take any parameters.
public Circle(int radius)
{
    Console.WriteLine("Circle, r={0} is created", radius);
}
This constructor takes one parameter — the radius.
public Circle() : this(1) 
{

}
This is the constructor without a parameter. It simply calls the other constructor and gives it a default radius of 1.
$ ./constructorchaining.exe 
Circle, r=5 is created
Circle, r=1 is created
This is the output of the constructorchaining.exe program.

Class constants

C# enables to create class constants. These constants do not belong to a concrete object. They belong to the class. By convention, constants are written in uppercase letters.
using System;

public class Math 
{
    public const double PI = 3.14159265359;
}

public class ClassConstants
{
    static void Main()
    {
        Console.WriteLine(Math.PI);
    }
}
We have a Math class with a PI constant.
public const double PI = 3.14159265359;
The const keyword is used to define a constant. The public keyword makes it accessible outside the body of the class.
$ ./classconstant.exe 
3.14159265359
Running the example we see this output.

The ToString() method

Each object has a ToString() method. It returns a human-readable representation of an object. The default implementation returns the fully qualified name of the type of the Object. Note that when we call the Console.WriteLine() method with an object as a parameter, the ToString() is being called.
using System;

public class Being 
{
    public override string ToString()
    {
        return "This is Being class";
    }
}

public class ToStringMethod
{
    static void Main()
    {
        Being b = new Being();
        object o = new Object();
        
        Console.WriteLine(o.ToString());
        Console.WriteLine(b.ToString());
        Console.WriteLine(b);
    }
}
We have a Being class in which we override the default implementation of the ToString() method.
public override string ToString()
{
    return "This is Being class";
}
Each class created inherits from the base object. The ToString() method belongs to this object class. We use the override keyword to inform that we are overriding a method.
Being b = new Being();
object o = new Object();
We create one custom defined object and one built-in object.
Console.WriteLine(o.ToString());
Console.WriteLine(b.ToString()); 
We call the ToString() method on these two objects.
Console.WriteLine(b);
As we have specified earlier, placing an object as a parameter to the Console.WriteLine() will call its ToString() method. This time, we have called the method implicitly.
$ ./override.exe 
System.Object
This is Being Class
This is Being Class
This is what we get when we run the example.

Inheritance

The inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called baseclasses. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of the base classes (ancestors).
using System;

public class Being 
{
    public Being()
    {
        Console.WriteLine("Being is created");
    }
}

public class Human : Being
{
    public Human()
    {
        Console.WriteLine("Human is created");
    }
}

public class Inheritance
{
    static void Main()
    {
        new Human();
    }
}
In this program, we have two classes. A base Being class and a derived Human class. The derived class inherits from the base class.
public class Human : Being
In C#, we use the colon (:) operator to create inheritance relations.
new Human();
We instantiate the derived Human class.
$ ./inheritance.exe 
Being is created
Human is created
We can see that both constructors were called. First, the constructor of the base class is called, then the constructor of the derived class.
A more complex example follows.
using System;

public class Being 
{
    static int count = 0;

    public Being()
    { 
        count++;
        Console.WriteLine("Being is created");
    }

    public void GetCount()
    {
        Console.WriteLine("There are {0} Beings", count);
    }
}

public class Human : Being
{
    public Human()
    {
        Console.WriteLine("Human is created");
    }
}

public class Animal : Being
{
    public Animal()
    {
        Console.WriteLine("Animal is created");
    }
}

public class Dog : Animal
{
    public Dog()
    {
        Console.WriteLine("Dog is created");
    }
}

public class Inheritance2
{
    static void Main()
    {
        new Human();
        Dog dog = new Dog();
        dog.GetCount();
    }
}
We have four classes. The inheritance hierarchy is more complicated. The Human and the Animalclasses inherit from the Being class. The Dog class inherits directly from the Animal class and indirectly from the Being class. We also introduce a concept of a static variable.
static int count = 0;
We define a static variable. Static members are members that are shared by all instances of a class.
public Being()
{ 
    count++;
    Console.WriteLine("Being is created");
}
Each time the Being class is instantiated, we increase the count variable by one. This way we keep track of the number of instances created.
public class Animal : Being
...

public class Dog : Animal
...
The Animal inherits from the Being and the Dog inherits from the Animal. Indirectly, the Dog inherits from the Being as well.
new Human();
Dog dog = new Dog();
dog.GetCount();
We create instances from the Human and from the Dog classes. We call the GetCount() method of the Dog object.
$ ./inheritance2.exe 
Being is created
Human is created
Being is created
Animal is created
Dog is created
There are 2 Beings
The Human calls two constructors. The Dog calls three constructors. There are two Beings instantiated.
We use the base keyword to call the parent's constructor explicitly.
using System;

public class Shape 
{
    protected int x;
    protected int y;

    public Shape() 
    {
        Console.WriteLine("Shape is created");
    } 

    public Shape(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

public class Circle : Shape
{
    private int r;    

    public Circle(int r, int x, int y) : base(x, y)
    {
        this.r = r;
    }

    public override string ToString()
    {
        return String.Format("Circle, r:{0}, x:{1}, y:{2}", r, x, y);
    }
}

public class Shapes
{
    static void Main()
    {
        Circle c = new Circle(2, 5, 6);
        Console.WriteLine(c);
    }
}
We have two classes: the Shape class and the Circle class. The Shape class is a base class for geometrical shapes. We can put into this class some commonalities of the common shapes, like the x, y coordinates.
public Shape() 
{
    Console.WriteLine("Shape is created");
} 
public Shape(int x, int y)
{
    this.x = x;
    this.y = y;
}
The Shape class has two constructors. The first one is the default constructor. The second one takes two parameters: the x, y coordinates.
public Circle(int r, int x, int y) : base(x, y)
{
    this.r = r;
}
This is the constructor for the Circle class. This constructor initiates the r member and calls the parent's second constructor, to which it passes the x, y coordinates. Have we not called the constructor explicitly with the base keyword, the default constructor of the Shape class would be called.
$ ./shapes.exe 
Circle, r:2, x:5, y:6
This is the output of the example.

Abstract classes and methods

Abstract classes cannot be instantiated. If a class contains at least one abstract method, it must be declared abstract too. Abstract methods cannot be implemented; they merely declare the methods' signatures. When we inherit from an abstract class, all abstract methods must be implemented by the derived class. Furthermore, these methods must be declared with the same of less restricted visibility.
Unlike Interfaces, abstract classes may have methods with full implementation and may also have defined member fields. So abstract classes may provide a partial implementation. Programmers often put some common functionality into abstract classes. And these abstract classes are later subclassed to provide more specific implementation. For example, the Qt graphics library has aQAbstractButton, which is the abstract base class of button widgets, providing functionality common to buttons. Buttons Q3ButtonQCheckBoxQPushButtonQRadioButton, and QToolButton inherit from this base abstract class.
Formally put, abstract classes are used to enforce a protocol. A protocol is a set of operations which all implementing objects must support.
using System;

public abstract class Drawing
{
    protected int x = 0;
    protected int y = 0;

    public abstract double Area();

    public string GetCoordinates()
    {
        return string.Format("x: {0}, y: {1}", this.x, this.y);
    }
}

public class Circle : Drawing
{
    private int r; 

    public Circle(int x, int y, int r)
    {
        this.x = x;
        this.y = y;
        this.r = r;
    }

    public override double Area()
    {
        return this.r * this.r * Math.PI;
    }

    public override string ToString()
    {
        return string.Format("Circle at x: {0}, y: {1}, radius: {2}", 
            this.x, this.y, this.r);
    }
}

public class AbstractClass
{
    static void Main()
    {
        Circle c = new Circle(12, 45, 22);
        Console.WriteLine(c);
        Console.WriteLine("Area of circle: {0}", c.Area());
        Console.WriteLine(c.GetCoordinates());
    }
}
We have an abstract base Drawing class. The class defines two member fields, defines one method and declares one method. One of the methods is abstract, the other one is fully implemented. TheDrawing class is abstract because we cannot draw it. We can draw a circle, a dot or a square. TheDrawing class has some common functionality to the objects that we can draw.
public abstract class Drawing
We use the abstract keyword to define an abstract class.
public abstract double Area();
An abstract method is also preceded with the abstract keyword.
public class Circle : Drawing
A Circle is a subclass of the Drawing class. It must implement the abstract Area() method.
public override double Area()
{
    return this.r * this.r * Math.PI;
}
When we implement the Area() method, we must use the override keyword. This way we inform the compiler that we override an existing (inherited) method.
$ ./abstractclass.exe 
Circle at x: 12, y: 45, radius: 22
Area of circle: 1520.53084433746
x: 12, y: 45
We see the output of the abstractclass.exe program.

No comments:

Post a Comment