Skip to main content

Abstract Class in C#

              ABSTRACT CLASS


Definition
Abstract classes are classes which cannot be instantiated ie. We cannot create object of abstract class.
It acts as base class for other class. An abstract class contains abstract as well as non abstract member functions, the abstract member functions are implemented by the derived class.

Purpose
The purpose of abstract class is to provide basic  or default functionality  as well as common functionality that multiple derived class can share and override.

Properties
·         Abstract class cannot be instantiated
·         It can be used as base class only
·         It contains both abstract as well as non abstract member functions.
·         Abstract class is not sealed as sealed  access modifier prevents a class from being inherited
·         A non abstract class deriving an abstract class should  implementing all abstract member functions of the parent abstract class.
·         An abstract class can be inherited from a class and one or more interfaces.
·         An Abstract class can has access modifiers like private, protected, internal with class members. But abstract members cannot have private access modifier.
·         An Abstract class can has instance variables (like constants and fields).
·         An abstract class can has constructors and destructor.
·         An abstract method is implicitly a virtual method.
·         Abstract properties behave like abstract methods.
·         An abstract class cannot be inherited by structures.
·         An abstract class cannot support multiple inheritance.


abstract class ShapesClass
{
 abstract public int Area();
}
class Square : ShapesClass
{
 int side = 0;

 public Square(int n)
 {
 side = n;
 }
 // Override Area method
 public override int Area()
 {
 return side * side;
 }
}

class Rectangle : ShapesClass
{
 int length = 0, width=0;

 public Rectangle (int length, int width)
 {
 this.length = length;
 this.width = width;
 }
 // Override Area method
 public override int Area()
 {
 return length * width;
 }
}


Common design guidelines for Abstract Class
·         Don't define public constructors within abstract class. Since abstract class cannot be instantiate and constructors with public access modifiers provides visibility to the classes which can be instantiated.
·         Define a protected or an internal constructor within an abstract class. Since a protected constructor allows the base class to do its own initialisation when sub-classes are created and an internal constructor can be used to limit concrete implementations of the abstract class to the assembly which contains that class.
When to use
·         Need to create multiple versions of your component since versioning is not a problem with abstract class. You can add properties or methods to an abstract class without breaking the code and all inheriting classes are automatically updated with the change.
·         Need to to provide default behaviours as well as common behaviours that multiple derived classes can share and override.


//Abstract Class
abstract class absClass
{
               }

//Abstract class with abstract member functions
abstract class absClass
{
  public abstract void abstractMethod();
               }
//Abstract class with non abstract member functions
abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
               }

//Sample Program

using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0},
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}


Abstract class with two abstract member functions . Its implementation in two separate
Derived class.

//Abstract Class1
abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers
    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2
class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}


//Implementation of abstract properties

/Abstract Class with abstract properties
abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}

class absDerived:absClass
{
    //Implementing abstract properties
    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}


Abstract class cannot be sealed
//Incorrect
abstract sealed class absClass
{
}


An abstract method cannot be private
//Incorrect
private abstract int MultiplyTwoNumbers();

The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.

An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.

//Incorrect
public abstract virtual int MultiplyTwoNumbers();



An abstract member cannot be static.
//Incorrect
public abstract static int MultiplyTwoNumbers();



Abstract class vs. Interface
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
An example of interface:
interface iSampleInterface
{
  //All methods are automaticall abstract
  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}


Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.


Comments

Popular posts from this blog

Gemini software Dot net interview question for experienced

Gemini Interview questions 4-8 year experienced Dot net professional Gemini Interview questions 4-8 year experienced Dot net professional 1,Asp .net mvc request life cycle. 2,How routing works 3,Where codes for routing are written 4,What is attribute based routing in aap.net Mvc 5,Is multiple routes possible on a single action method. 6,What is action filters. 7,what is authentication and authorization filters 8,What are the types of authentication 8,What is the use of data annotation 9,Can we fire data annotation in client side. 10,What is model binding 11,what are Html helpers

15 Essential jQuery Interview Questions

15 Essential jQuery Interview Questions 15 Essential jQuery Interview Questions 1,Explain what the following code will do: $( "div#first, div.first, ol#items > [name$='first']" ) Ans:This code performs a query to retrieve any element with the id first, plus all elements with the class first, plus all elements which are children of the element and whose name attribute ends with the string "first". This is an example of using multiple selectors at once. The function will return a jQuery object containing the results of the query. 2,What is wrong with this code, and how can it be fixed to work properly even with buttons that are added later dynamically? // define the click handler for all buttons $( "button" ).bind( "click", function() {     alert( "Button Clicked!" ) }); /* ... some time later ... */ // dynamically add another button to the page $( "html" ).append( " Click...

ASP .Net MVC

ASp .Net MVC 1. Explain MVC (Model-View-Controller) in general? MVC (Model-View-Controller) is an architectural software pattern that basically decouples various components of a web application. By using MVC pattern, we can develop applications that are more flexible to changes without affecting the other components of our application. §    “Model”, is basically domain data. §    “View”, is user interface to render domain data. §    “Controller”, translates user actions into appropriate operations performed on model. 2. What is ASP.NET MVC? ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-View-Controller) architectural design pattern. Microsoft has streamlined the development of MVC based applications using ASP.NET MVC framework. 3. Difference between ASP.NET MVC and ASP.NET WebForms? ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas ASP.NET MVC uses Front con...