Sunday 18 October 2015

Runtime polymorphism













We will declare vehicle inteface here, interface will tell what should implement not how to implement.
    //Vehicle.cs
    public interface Vehicle
    {
        void engine();
        void breaks();
    }



In above we created vehicle as interface. So now here we will create bus as abstract class, because we have different types of buses with some common operarions and individual operations
    //Bus.cs
    public abstract class Bus : Vehicle
    {
        public abstract void engine();

        public void breaks()
        {
            Console.WriteLine("Bus has two breaks");
        }
    }

In above we created Vehicle as interface and bus as abstract class which implements vehicle interface. So now here we will create RedBus, Volvo as concrete class by implementing all other operations which are left as abstract in its superclass(Bus.cs).
    //RedBus.cs
    public class RedBus : Bus
    {
        public override void engine()
        {
            Console.WriteLine("RedBus engine capacity is 40 kmph");
        }
    }

    //Volvo.cs
    public class Volvo : Bus
    {
        public override void engine()
        {
            Console.WriteLine("Volvo engine capacity is 100 kmph");
        }
    }

So now develop a runtime polymorpic class to use all Vehicles operations. Here we will build bus as per user choice of bus type here in this case Volvo and RedBus.
    //BuildBus.cs
    public class BuildBus
    {
        public void assignVehicle(Vehicle v)
        {
            v.breaks();
            v.engine();
        }
    }


    //OrderBus.cs
    class OrderBus
    {
        static void Main(string[] args)
        {
            BuildBus volvo = new BuildBus();
            volvo.assignVehicle(new Volvo());
            Console.WriteLine("------------------");
            BuildBus redBus = new BuildBus();
            redBus.assignVehicle(new RedBus());
        }
    }

Output:


No comments:

Post a Comment