← Back to C# Course | Chapter 7: Inheritance | Lesson 6 of 6

Polymorphism क्या है

Polymorphism का मतलब है कई रूप: अलग-अलग objects एक ही command का अपने तरीके से जवाब दे सकते हैं। हर animal को बोलने को कहें, और dog भौंकता है जबकि cat म्याऊं करती है।

In this page:

  1. Polymorphism
Syntax
csharp
BaseType variable = new DerivedType();
variable.MethodName();   // runs the DerivedType override

List<BaseType> items = new List<BaseType> { new DerivedA(), new DerivedB() };

Polymorphism

Polymorphism आपको एक shared base type या interface के ज़रिए अलग-अलग derived types के objects को एक जैसा treat करने देता है, जबकि हर एक अब भी अपना overridden behavior चलाता है।

एक single List<Shape> circles, squares, और triangles रख सकता है, और हर एक पर Area() call करना सही implementation अपने आप invoke करता है। यही वजह है कि overriding genuinely उपयोगी है, सिर्फ syntax नहीं।

Note: Polymorphism ही वजह है कि आप एक loop लिख सकते हैं जो सही से काम करता है चाहे हर object असल में कौन सी subclass हो।

उदाहरण: Polymorphism

markup
using System;
using System.Collections.Generic;

class Shape
{
    public virtual double Area() => 0;
}

class Circle : Shape
{
    public double Radius;
    public Circle(double r) { Radius = r; }
    public override double Area() => Math.PI * Radius * Radius;
}

class Square : Shape
{
    public double Side;
    public Square(double s) { Side = s; }
    public override double Area() => Side * Side;
}

class Program
{
    static void Main(string[] args)
    {
        List<Shape> shapes = new List<Shape> { new Circle(2), new Square(3) };

        foreach (Shape s in shapes)
        {
            Console.WriteLine(s.Area());
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. virtual और override भूल जाना, जिससे base reference के ज़रिए base version call होता है।
  2. किसी base reference के ज़रिए एक derived-only method call करना, जो compile नहीं होता।
  3. new से method hiding को असली overriding के साथ confuse करना।
चैप्टर सारांश
  • Inheritance किसी class को दूसरी class reuse करने देता है, base parent को access करते हुए।
  • Method overriding और polymorphism derived classes को behavior बदलने देते हैं।
  • Abstract और sealed classes नियंत्रित करती हैं कि classes कैसे extend हो सकती हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.