Sponsored Ad

Wednesday, June 1, 2011

Can we have Non Abstract Method in Abstract Class in C#

Yes, you can have non abstract methods in abstract class. Along with non abstract methods you can also have abstract methods in abstract class.

You can not directly use non abstract methods of abstract class, for the same you have to derive a class from abstract class and give new implementation of non abstract method in derived class.

In below example there is abstract class abstract_class_example which is having the non abstract method non_abstract_method_example.

 

using System;

namespace MyApp
{
    public class abstract_examples
    {
        public static void Main(string[] args)
        {
            Console.ReadLine();
        }

        //abstract class with non abstract methods
        public abstract class abstract_class_example
        {
            public void non_abstract_method_example()
            {
                Console.WriteLine("Non Abstract Method Example.");
            }
        }     
    }
}

Can a Class can be Derived from Abstract Class in C#

Yes, you can derive a class from abstract class the code is given below. write a abstract class with abstract function and drive a class from this abstract class and override the abstract method in derive class and give implementation. while calling this method you need to create instance of derive class only because parent class don't have any implementation.

Program Output

Code to derive a class from abstract class:

using System;

namespace MyApp
{
    public class abstract_derived_class
    {
        public static void Main(string[] args)
        {
            derived_class obj = new derived_class();
            obj.my_method();

            Console.ReadLine();
        }

        public abstract class abstract_class
        {
            public abstract void my_method();          
        }

        public class derived_class : abstract_class
        {
            public override void my_method()
            {
                Console.WriteLine("Derived Class Method.");
            }
        }
    }
}

Sponsored Ad

Followers

Follow Us