Sunday, August 20, 2017

Abstract

Abstract class used for hiding the internal detail and showing functionality.If there are two or more class has the same functionality and that functionality declares on base class have no permission to instantiate this type of situation we have to use an abstract class.An abstract method has no implementation.Abstract class, we can't instantiate. We can use an Abstract class as a Base Class. An Abstract method must be implemented in the non-Abstract class using the override keyword. We can derive this class in another class and again we can override the same abstract method with it.

Features:
  • In an abstract class can implement code with non-Abstract methods.
  • An abstract class can inherit from a class and one or more interfaces.
  • An Abstract class can have modifiers for methods, properties etc.
  • An Abstract class can have constants and fields and implement a property.
  • An abstract class can have constructors or destructors.
  • An abstract class cannot be inherited from by structures.
  • In an abstract class Multiple inheritances not possible. 


Example:

abstract class BClass  
{
    protected int _x = 100;
    protected int _y = 150;
    public abstract void AbstractMethod();   
    public abstract int X    { get; }
    public abstract int Y    { get; }
}

class DClass : BClass
{
    public override void AbstractMethod()
    {
        _x++;
        _y++;
    }

    public override int X   
    {
        get
        {
            return _x + 5;
        }
    }

    public override int Y   
    {
        get
        {
            return _y + 5;
        }
    }

    static void Main()
    {
        DClass o = new DClass();
        o.AMethod();
        Console.WriteLine("x = {0}, y = {1}", o.X, o.Y);
    }
}



 Result: x = 106, y = 156

No comments:

Post a Comment