Wednesday, December 15, 2010

Code Example for abstract and interface

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

namespace ConsoleApplication3
{
   abstract class test
    {
        abstract public void print();
        public int y; //can initialise fields 
    }

     class Program:test

    {
         //abstract class
        public override void print()
        {
            x = 10;
            Console.WriteLine("Abstract  : test value :"+y.ToString());
        }
         //end of abstract
        public int x;
     }
     interface test_interface
     {
        void test();
         // int x; it gives the error as Error    "Interfaces cannot contain fields"            
     }
     class tt:Program,test_interface //inherit base class and interface
    {
        //interface
        public  void test()
        {
           
            Console.WriteLine("interface value");
        }
        //end
     }

   
    class main_class
    {
        static void Main(string[] args)
        {
           
            Program pp = new Program();//create instance for base class for abstract only;
            tt te=new tt(); //for both abstract and derived class
            te.print();//abstract
            te.test();//interface

            pp.print();//
           
            pp.x = 100;
            Console.WriteLine(pp.x);
            test_interface ttt = (test_interface)te;//type casting into interface type
            ttt.test();
        }
    }
}