Friday, 13 July 2018

Inheritance in c#

Base Abstract  Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearnInheritance
{
    public abstract class BaseAbstractClass
    {
        public abstract string PrintAbstract();// can not contain the body
       

        public virtual string PrintVirtual()
        {
            return "Base virtual Class";
        }
    }
}


Interface Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearnInheritance
{
    interface Interface
    {
        string PrintInterface();
    }
}


Derived  Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearnInheritance
{
    class DerivedClass : BaseAbstractClass, Interface
    {
        public override string PrintAbstract()
        {
            return "Derived Abstract Class";
        }

        public override string PrintVirtual()
        {
            return "Derived virtual Class";
        }

        public string PrintInterface()
        {
            return "Derived Interface Class";
        }
    }
}



Secondary Derived Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearnInheritance
{
    class SecondDerivedClass : DerivedClass, Interface
    {
        public override string PrintAbstract()
        {
            //return base.PrintAbstract();
            return "Second Derived Class";
        }
        public new string PrintInterface()
        {
            return "Second Derived Interface Class";
            //return base.PrintInterface();
        }
    }
}


Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearnInheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass dc = new DerivedClass();
            Console.WriteLine(dc.PrintAbstract());
            Console.WriteLine(dc.PrintVirtual());
            Console.WriteLine(dc.PrintInterface());
            SecondDerivedClass sdc = new SecondDerivedClass();
            Console.WriteLine(sdc.PrintAbstract());
            Console.WriteLine(sdc.PrintInterface());
        }
    }
}


Output


No comments:

Post a Comment