C Sharp Abstract

C# Abstract

To achieve abstraction in C#, the Abstract classes are used. To hide the internal details and to display only the functionality, the process of abstraction is used in C#. There are two ways to achieve Abstraction: Abstract class and Interface. Abstract methods are necessary for abstraction and are present in the Abstract class and interface.

Abstract Method:

An abstract method is the one that is declared abstract. It has no body. Declared inside only the abstract class the implementation of the abstract method must be provided by the derived classes. Being internally a virtual method an abstract method in C# can be overridden by the derived class. In the abstract method declaration, the static and virtual modifiers can’t be used.

Syntax:

public abstract void color();  

Example:

using System;  
public abstract class Flower  
{  
    public abstract void color();  
}  
public class Rose : Flower  
{  
    public override void color()  
    {  
        Console.WriteLine("Red Rose!!");  
    }  
}  
public class Lily : Flower  
{  
    public override void color()  
    {  
        Console.WriteLine("White Lily!!");  
    }  
}  
public class TestAbstract  
{  
    public static void Main()  
    {  
        Flower f;  
        f = new Rose();  
        f.color();  
        f = new Lily();  
        f.color();  
    }  
}

Output:

Explanation:

In the above example, the abstract class Flower has one abstract method color(). The derived classes, Rose and Lily provides its implementation. The derived classes, Rose and Lily, however, have a different implementation.

C# Abstract class:

A class that is declared abstract is called an abstract class in C#. Containing both abstract and non-abstract methods, an abstract class in C# however, can’t be instantiated. Derived classes provide the implementation of an abstract class in C#. To provide the implementation of all the abstract methods, the derived class is forced.

Syntax:

public abstract class Flower

Example:

using System;  
public abstract class Flower  
{  
    public abstract void color();  
}  
public class Rose : Flower  
{  
    public override void color()  
    {  
        Console.WriteLine("Red Rose!!");  
    }  
}  
public class Lily : Flower  
{  
    public override void color()  
    {  
        Console.WriteLine("White Lily!!");  
    }  
}  
public class TestAbstract  
{  
    public static void Main()  
    {  
        Flower f;  
        f = new Rose();  
        f.color();  
        f = new Lily();  
        f.color();  
    }  
}

Output:

Explanation:

In the above example, the abstract class Flower has one abstract method color(). The derived classes, Rose and Lily provides its implementation. The derived classes, Rose and Lily, however, have a different implementation.

Please follow and like us:
Content Protection by DMCA.com