Sunday, 8 April 2018

Abstraction in .Net

Encapsulation: Encapsulate hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.

Abstraction: Abstraction is used to showing what is relevant but in a higher degree(class, interface). Clients use an abstract class(or interface) do not care about who or which it was, they just need to know what it can do.

Constructor in abstract class
There's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:

abstract class Animal
   {
       public string DefaultMessage { get; set; }

       public Animal()
       {
           Console.WriteLine("Animal constructor called");
           DefaultMessage = "Default Speak";
       }
       public virtual void Speak()
       {
           Console.WriteLine(DefaultMessage);
       }
   }

    class Dog : Animal
    {
        public Dog(): base()//base() redundant.  There's an implicit call to base here.
        {
            Console.WriteLine("Dog constructor called");
        }
        public override void Speak()
        {
            Console.WriteLine("Custom Speak");//append new behavior
            base.Speak();//Re-use base behavior too
        }
    }

Although we cannot directly construct an Animal with new, the constructor is implicitly called when we construct a Dog.

OUTPUT:
Animal constructor called
Dog constructor called
Custom Speak
Default Speak

IN Short :
Encapsulation: hiding data using getters and setters etc.
Abstraction: hiding implementation using abstract classes and interfaces etc.

2 comments:

  1. this post "abstraction in net was very usefull for me and friends, nice post
    iweblogsite

    ReplyDelete
  2. Nice Article,Good information,keep sharing.
    https://nareshit.in/software-training-institute-bangalore/

    ReplyDelete

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (9) Web Service (1) XMl (1)