Translate

Thursday 26 June 2014

Why we can't create object to ABSTRACT & INTERFACE classes?

             We cannot create object for interface and abstract class. Because, it is possible that some methods are not implemented within interface or abstract class. In the case of an interface, non of the methods are implemented and an abstract class, abstract method cannot implemented.

Without a full implementation, how could we instantiate the class.

Runtime Polymorphism and Method hiding

Runtime polymorphism:

By runtime polymorphism we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.



namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class shape
        {
            public int _radius = 5;
            public virtual double getArea()
            {
                return 0;
            }
        }
        public class circle : shape
        {
            public override double getArea()
            {
                return 3.14 * _radius * _radius;
            }
        }
        public class sphere : shape
        {
            public override double getArea()
            {
                return 4 * 3.14 * _radius * _radius;
            }
        }
        static void Main(string[] args)
        {
            shape objBaseRefToDerived = new circle();  // run time polymorphism
            objBaseRefToDerived.getArea();

            shape objBaseRefToDerived1 = new sphere();  // run time polymorphism
            objBaseRefToDerived1.getArea();

            Console.ReadLine();
        }
    }
}

we want calculate area of circle, at the time we have to create object like

BaseclassName obj=derivedclassName()  

--------------------------------------------------------------------------------------------------
Method Hiding:

namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {

            public new void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}

Output is:? Show From Base Class.