Showing posts with label oops. Show all posts
Showing posts with label oops. Show all posts

Saturday, October 3, 2015

Access modifiers in C#.NET with exampls

Introduction:

Access modifier are the defined level of permission to access properties and methods. By declaring this access modifiers we defining a variable or a event can be access from assembly to within that class. Lets see how.

Description:

There are 4 major access modifiers in C#. These are...

  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected Internal
Public:
Using Public a event or a variable can be accessed from outside of  the class, where it belongs. And also from the outside of the assembly. 

class ClassTest
{
    //Public method
    public void MethodPublic()
    {
        // defination of MethodPublic
    }
}

// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();
           
        objClassTest.MethodPublic(); // valid code to access.  
    }
}

Private:
It restricts the use of methods and variables only within the the class itself. It cant be used from the outside of the class. As you declare a private constructor of a class that class can't be access from the outside that class, you can't create an object of that class,

Example 1: Private keyword
class ClassTest
{
    //Private method
    private void MethodPrivate()
    {
        // defination of MethodPrivate
    }
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();

        objClassTest.MethodPrivate(); // invalid code to access.  
    }
}


Example 2: Private Constructor 
class ClassTest
{
    private ClassTest() { } // private constructor
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        // invalid code. can't create an object of this class
        ClassTest objClassTest = new ClassTest();
    }
}

Protected:
This allows variables  and methods to access from that class and the sub class of the class. That means that methods can be access within that class and from the classes, which actually inheriting that class. 

class ClassTest
{
    //Protected variable
    protected int _a;
}

class ClassTest2 : ClassTest
{
    ClassTest2()
    {
        this._a = 10; // can access from this class
    }
}

class ClassTest3
{
    ClassTest3()
    {
        this._a = 10; // can't access from this class
    }
}

Internal:
Internal is introduces in C#. In JAVA we don't have this access modifier. This allows the access after Protected. As Protected it is also allow to access the methods and variables from that class and the sub classes of that class. It added the assembly into it. That means the variables and methods can be access within the assembly where the class belongs. Now make that sure that here we are talking about Namespace, because Namespace and assembly are slightly different. An assembly can hold more than one Namespace. Assemblies are actually the dll of the project.

class ClassTest
{
    internal void MethodInternal()
    {
        // do your code
    }
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();

        objClassTest.MethodInternal(); // valid code to access.  
    }
}

Protected Internal:
Protected Internal allows you to access the variables and methods to access from that class and sub classes of that class. Also allows to access within the same assembly. Means in protected if the class is inheriting the super class and the method or variable is protected then the assembly doesn't matter to access. But in the Internal the assembly matters if the class is inheriting the super class. That is why we use Protected Internal access modifier. 

class ClassTest
{
    protected internal string name; // protected internal
    public void print()
    {
        Console.WriteLine("\nMy name is " + name);
    }
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();
        // Accepting value in protected internal variable
        objClassTest.name = "Arka";
        objClassTest.print();
    }
}

In sort:

Public: Any where from the class
Private: Only within the class
Protected: Only within that class and the sub classes of that class
Internal: Within the assembly of the class
Protected Internal: Within that class, sub classes of that class and and assembly.

Hope it will clear your concept about the access modifiers. Don't forget to post your valuable comments. 

Friday, October 2, 2015

Difference between Encapsulation and Abstraction in OOPs (C#.NET)

Introduction:
There are 4 major properties of Object Oriented Programming (OOPs) as you know. These are

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
Among of these four properties or features we will discuss about the first two (Abstraction and Encapsulation) in this post. 

Description:

So what actually Abstraction and Encapsulation are? Lets us know with an example

Abstraction:
Abstraction is a process to abstract or hide the functionality and provide users or other programmers to use it only. Like for the method Console.WriteLine(), no one knows what actually happening behind the function calling. We  are just using it by calling and passing the arguments. This is the thing called Abstraction. 

Encapsulation:
Encapsulation means to encapsulate or put every thing into one thing and provide others to use it. Like in a shaving kit there are all the necessary kits are available. And also these kits are available as loose in market. But the shaving kit is encapsulate every other kits into a small bag and provide user to use it. 

Hope so now you have a basic idea about both of these properties, Lets see a real world example of encapsulation and abstraction.

Lets assume you have to create a method to insert an users data and pass it to other developers to use. So first create a class and add a method to insert the data into database with validation. 

There will be three fields 
  1. Name 
  2. Email
  3. Phone number
So these inputs have to validate first and then insert into db.

First create a class with all methods

class User
{
    public bool AddUser(string name, string email, string phone)
    {
        if (ValidateUser(name, email, phone))
        {
            if (AddtoDb(name, email, phone) > 0)
            {
                return true;
            }
        }
        return false;
    }

    private bool ValidateUser(string name, string email, string phone)
    {
        // do your validation
        return true;
    }

    private int AddtoDb(string name, string email, string phone)
    {
        // Write the Db code to insert the data
        return 1;
    }
}

As you can see there are three methods are written in this User class. 
  • AddUser: To call from outside the class. That is why the access modifier is public.
  • validateUser: To validate the user's details. Can't access from out side the class. Its private.
  • AddtoDb: To insert data into database table and again it is private, can't access from out side the class.
Now another user will just call AddUser method with parameters. And that user has no idea what is actually happening inside the method. I didn't write the code to validate and insert into db, as you can get it from others examples. We will discuss about it later. 

To call the AddUser method do like following. 

class Program
{
    static void Main(string[] args)
    {
        User objUser = new User();
        bool f = objUser.AddUser("Arka", "ark@g.com", "1234567890");
    }
}

Now come back to the main discussion.

Here we are hiding the procedure of adding data into database from other users, this is Abstraction. And putting all the three methods into one User class and provide other user to use it that is called Encapsulation. 

So procedure hiding is Abstraction and putting every necessary things into one is Encapsulation.   
Hope so you have cleared your doubt about the concept of  Encapsulation and Abstraction. 

Friday, September 12, 2014

Polymorphism(Method Overloading and Overriding) in C#

Today's topic is a old one. Maximum among you are familiar with this topic. I am talking about one of the OOPs(Object Oriented Programming) feature polymorphism. In your college life you had come to know about polymorphism, but today I will discuss about this very known topic with the help of C#. As usual I have taken Find Area as an example like you did in your college.

Lets come to the point straight way.  Polymorphism has two parts.
  1. Method Overloading
  2. Method Overriding
Method Overloading :
So, lets start with the Method Overloading. Create a new project and take two textboxes, one button and one label for showing result.  Before starting one question came into the mind.. What actually method overloading is. Before this let me say about one very important issue about methods or function. A method name depends not only its name but also on its return type and argument. If you keep the name same and create a new method with a different return type and arguments it will act as a different method. This is  Method overloading. Calling the particular method, which has named more than one, but with distinct return type and argument.

In calculating area of a rectangle and a circle, the only difference is no of argument. In the first case you have to provide two argument(length and breath) but in the case of circle only one(radius) is enough to get the area. So, we will create two methods named FindArea() with 2 different argument. Lets check the following example.

/// 
/// For circle
/// 
/// 
/// 
private Double FindArea(string r)
{
     return 22 / 7 * Math.Pow(Convert.ToInt32(r),2);
}

/// 
/// For rectangle
/// 
/// 
/// 
/// 
private int FindArea(string l, string b)
{
     return (Convert.ToInt32(l) * Convert.ToInt32(b));
}        

Your methods are ready. Now you have to call these. For this generate click event of the button, and write down the following code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
 /* For rectangle */
 if (txt1.Text != "" && txt2.Text != "")
 {
  lblArea.Text =  FindArea(txt1.Text.Trim(), 
   txt2.Text.Trim()).ToString();
 }
 /* for circle */
 else if (txt1.Text != "" && txt2.Text == "")
 {
  lblArea.Text = FindArea(txt1.Text.Trim()).ToString();
 }
 else
 {
  lblArea.Text = "Fill any of the two input box !";
 }
}

I hope it is clear to you what is method overloading and how its work. Now lets move to method overriding.

Method Overriding :

Not like method overloading its about inheritance. Before starting discussing about the inheritance is important. Inheritance is one of the property of OPPs programming concept, to get the all properties and methods of a parent class to the child class. Like all of your parents property is yours, because you are inheriting your parents.

So here we have taken two classes, parent.cs and child.cs and child.cs is inheriting parent.cs. So what ever variables or methods are declare in the parent.cs is accessible for child.cs.

We have declare abc() method in both class and creating  an object of child class. Using this object we are calling the abc() method. Now in the child class there are two abc() methods are present. One is its own and another is inherited from parent class. So, which method will be called? Answer is child class one. The child class method will override the parent class method to execute. Lets check the code once.
public class parent
{
 public parent() { }

 public string abc()
 {
  return "parent -> abc";
 }
}

public class child : parent
{
 public child() { }

 public string abc()
 {
  return "child -> abc";
 }
}

Now call the method.

child obj = new child();
Response.Write(obj.abc());

Output : child -> abc

Hope so both are clear for you, for your help you can download the full source code here.

Popular Posts

Pageviews