Sunday, 15 July 2012

Encapsulation in Object Orientation with Example


Overview of Object Orientation


Class:  A class is a template / skeleton / blueprint for creating an object.

Object:  An Object is an entity that has properties for validations, methods for functionality and events for depicting the change of state.

Every object has the data and behavior with which they are differed. Data associated at any given instance of time is the state of an object.

Component: A ready to use third party object can be called as a Component. It can be replaced without any changes in the application. A component is generally used by a programmer as an object.

Loosely coupled objects are better than tightly coupled objects i.e. the lesser the information given to other objects the better it is as the objects are loosely coupled the dependencies are less and stronger security.

Object Oriented Application: It’s a collection of related objects communicating with each other, exchanging messages with each other in a controlled environment as per the rules of the business.

Every object oriented language should have three features:
·         Encapsulation
·         Inheritance
·         Polymorphism

Encapsulation: Binding of data and behavior i.e. functionality of an object within a secured and controlled environment is encapsulation.

Inheritance: The Process of acquiring the existing functionality of the parent and with new added features and functionality by a child object is called inheritance.
The advantages of inheritance are Generalization, Extensibility and Reusability.
For example: A calculator is a generalized form of mathematical operations where as a Scientific calculator is an Extended and Specific form.

Polymorphism: An object in different forms and in each form it exhibits the same functionality but implemented in different ways.
For example:
A Teacher can take a form of Sport Teacher or Language Teacher and in both the forms it has the functionality Teach, but the implementation of Teach varies in both the objects and depends. Object

Creation and Instantiation: In MS.NET when an object is created there is no way to get the address of an object. Only the reference to the object is given through which we can access the members of the class for a given object.

When an object is created all the variables (value/ reference types) are allocated the memory in heap as a single unit and default values are set to them based on their data types.

Working with Methods

The methods of the object are used to describe the functionality / behavior.
 
·        An instance method of a class is always invoked only using a reference to an object. Thus it has access to all the data which is encapsulated by an object of that class.
·        A method requires parameter’s only for that data which it doesn’t have direct access to and but is needed for implementation of logic. Thus while writing a method in a class do not set to it any data as parameter or return type, if that data is already the data member in the same class. 
·         In a method “this” is reference to the current object on which the method is invoked.
·        If parameter/local variable and data member of a class have same name, the local variable takes the precedence over data member and if data member has to accessed in such a method then “this” can be used.
·        Whenever any of the business rules of an object or the integrity of the object is violated through a property or a method, it should respond by throwing a runtime exception.
·        The class should be always programmed in such a way that, it’s not specific to any particular type of application (Windows/Console/ClassLibrary/Service) so that the same class can reused in different applications / environment. For example, don’t use in class functionality like MessageBox or Console.WriteLine or Button or Label or TextBox etc….
 
Working with Object Properties
















·           A Property encapsulates a field member of the same class, so that the field member is not freely accessible outside the class and the required validation/restriction can be provided on it.

·           A property is made of two blocks i.e. Get and Set. Get block is invoked when the property is used on RHS and Set block is invoked when the property is used on LHS.

·           A property procedure doesn’t hold any data by itself instead it depends on some private field member of the class.

·           A Set block can validate the “value” before it is assigned to the field member of the class being encapsulated by the property. Similarly the field member can be validated before its value is returned in the Get block.

·           Using a property the field member can be restricted with either “ReadOnly” or “WriteOnly” access.

·           A class which has all its field members as Private and if required restricted access to these members is given using Public Properties is called “Fully Encapsulated Class”.

Syntax in C#:
Private <Datatype> _<propertyname>;
public <Datatype> <PropertyName>
{
 [private] get
{
return _<propertyname>;
}
[private] set
{
_<propertyname> = value;
}
}



A constructor is a member method of a class which is automatically executed / called as soon as the object of that class is created and thus it is ideally used for initializing the field members of the object.

1.          A constructor has same name as the class and doesn’t have a return type not even void.

2.          A constructor without a parameter is called default constructor and the one with parameters is called as Parameterized constructor.

3.          If a class doesn’t have any form of constructor, a public default constructor is automatically added to it by the language compiler.

4.          Copy Constructor is used to create a new object by duplicating the state of an existing object and this is done by copying the data members of existing object in new object data members.

Syntax in C#:
<Class name>()
{
                //default constructor
}
<Class name>(<datatype> p1, …)
{
                //parameterized constructor
}
<Class name>(<Class Name> <parname>) : this(. . .)
{
                //copy constructor
}

Assignment:

1.       Write a class called Math with three members Operand1, Operand2 and Result as Field members and of type integer.
2.       To this class add methods: Add, Subtract, Multiply and Divide
3.       Divide method should throw an Exception if Denominator is “0” (Zero).
4.       Operand1 and Operand2 as WriteOnly and Result as ReadOnly properties.
5.       The value of Operand1 must be in range of -100 to 100
6.       The value of Operand2 must be always less than Operand1 and it should not be “0”.
7.       In the Math class add all the three forms of constructor and in MathForm in “Create/Set” button Create the object using Parameterized Constructor. Eg: Math m = new Math(10,2).

Solution

Math.cs
using System;
class Math
{           
    private int _Operand1;
    private int _Operand2;
    private int _Result;
    public Math()
    //default constructor
    { }
    // Parameterized constructor
    public Math(int op1, int op2)
    {
        this.Operand1 = op1;
        this.Operand2 = op2;
    }
   //Copy constructor
    public Math(Math a)
    {
        this.Operand1 = a._Operand1;
        this.Operand2 = a._Operand2;
    }
    public int Operand1
    {
        set
        {
            if (value < -100 || value > 100)
                throw new ApplicationException("Operand1 value must be in the range of -100 and 100");
            _Operand1 = value;
        }
    }
    public int Operand2
    {
        set
        {
            if (value == 0)
                throw new ApplicationException("Operand2 value must be > 0");
            else if (_Operand1 <= value)
                throw new ApplicationException("Please make sure that the Operand2 is less than Operand1");
            _Operand2 = value;
        }
    }
    public int Result
    {
        get
        {
            return _Result;
        }
    }

//Following methods should not have any parameters because Operands are already members of the class and operation can be performed on them.
    public void Add()
    {
        _Result = _Operand1 + _Operand2;
    }
    public void Subtract()
    {
        _Result = _Operand1 - _Operand2;
    }
    public void Multiply()
    {
        _Result = _Operand1 * _Operand2;
    }
    public void Divide()
    {
        if (_Operand2 == 0)
            throw new ApplicationException("Denominator cannot be zero");
        _Result = _Operand1 / _Operand2;
    }
}

MathForm.cs
Math  obj;
 private void btnSet_Click(object sender, EventArgs e)
 {
     obj = new Math(int.Parse(txtOperand1.Text), int.Parse(txtOper
 }
 private void btnAdd_Click(object sender, EventArgs e)
 {
     obj.Add();
 }
 private void btnSubtract_Click(object sender, EventArgs e)
 {
     obj.Subtract();
 }
 private void btnMultiply_Click(object sender, EventArgs e)
 {
     obj.Multiply();
 }
 private void btnDivide_Click(object sender, EventArgs e)
 {
     obj.Divide();
 }
 private void btnGet_Click(object sender, EventArgs e)
 {
     txtResult.Text  = obj.Result.ToString();
 }

In case you have any queries. please contact me at sandeepsoni@deccansoft.com.
Don't forget to watch my C# videos on www.bestdotnettraining.com

1 comment:

  1. By default the compiler generates Default constructors.
    Do we need to take the extra effort to write default construtor again?
    If so when you assign values to it, don't you think that it is as good as Parameterised constructor?

    ReplyDelete