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

Method Overriding की जानकारी

Method overriding तब है जब कोई child class किसी inherited काम को अपने तरीके से करती है, जैसे कोई बच्चा Grandma की recipe को थोड़े बदलाव के साथ पकाए। Parent को virtual शब्द से कहना होगा कि method बदली जा सकती है।

In this page:

  1. Method Overriding
Syntax
csharp
class BaseClass
{
    public virtual ReturnType MethodName() { }
}

class DerivedClass : BaseClass
{
    public override ReturnType MethodName() { }
}

Method Overriding

कोई base class किसी method को virtual चिह्नित करती है ताकि derived classes override से इसके behavior को replace कर सकें।

Runtime पर, C# variable के declared type के बजाय object के असली type के आधार पर overridden version call करता है — यह polymorphism है। virtual/override के बिना, एक जैसे नाम वाला derived method सिर्फ base वाले को छुपा देता है बजाय override करने के।

Warning: base method पर virtual भूल जाने का मतलब है कि derived class में override compile नहीं होगा।

उदाहरण: Method Overriding

markup
using System;

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

class Circle : Shape
{
    public double Radius;

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Shape s = new Circle(3);
        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. base method में virtual भूल जाना, जिससे override की अनुमति नहीं मिलती।
  2. derived method में override भूल जाना, जो override करने के बजाय एक hiding warning बनाता है।
  3. किसी overriding method का return type या parameters बदलना, जो एक compile error है।
🔒

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.