Advertisement
//C# Example of Polymorphism
using System;
//Base class
class A
{
}
//class B is a derived class of class A
class B:A
{
}
class Polymorphism
{
public static void Main(String[] ar)
{
//Object of B is assigned and will be accessed from a reference variable of its own B class.
B ob1 = new B();
//Object of B is assigned and will be accessed from a reference variable of its base class, A.
A ob2 = new B();
//Object of B is assigned and will be accessed from a reference variable of base class of all classes, Object.
Object ob3 = new B();
}
}
//C# Example of Polymorphism
using System;
//An interface
interface A
{
}
//class B is implementing interface A
//Therefore, class B is derived class of A
class B:A
{
}
class Polymorphism
{
public static void Main(String[] ar)
{
//Object of B is assigned and will be accessed from a reference variable of its own B class.
B ob1 = new B();
//Object of B is assigned and will be accessed from a reference variable of its base class, A.
//Which is an interface
A ob2 = new B();
//Object of B is assigned and will be accessed from a reference variable
//of the base class of all classes, Object.
Object ob3 = new B();
}
}
Advertisement
//C# Compile-time polymorphism - method overloading
using System;
//Base class
class A
{
//Defining the method Message()
//This method takes an argument of its class type, A
public void Message(A ob)
{
Console.WriteLine("A");
}
}
//class B is inheriting class A i.e. Derived class
class B:A
{
//Defining an overloaded version of method Message()
//This version takes an argument of derived class type, B
public void Message(B ob)
{
Console.WriteLine("B");
}
}
class Poly
{
public static void Main(String[] ar)
{
//ob1 is declared of type A but it is pointing to object of its derived class, B
A ob1 = new B();
//Calling the overloaded method Message()
//By using the object of derived class, B
//Which is referenced by the reference variable of its base class, A
//This method is passed the object of derived class, B
ob1.Message(ob1);
}
}
A
//C# Runtime polymorphism or dynamic method dispatch, during method overriding
using System;
//Base class
class Vegetable
{
//Method Message() of base class Vegetable
public virtual void Message()
{
Console.WriteLine("Eat vegetables");
}
}
//Derived class
class Tomato:Vegetable
{
//Overriding the method Message() of base class Vegetable
public override void Message()
{
Console.WriteLine("Eat Tomatoes");
}
}
class Polymorphism
{
public static void Main(String[] ar)
{
Vegetable ob1= new Tomato(); //comment1
ob1.Message(); //comment2
}
}
Eat Tomatoes
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement