Method Overriding की जानकारी
Method overriding तब है जब कोई child class किसी inherited काम को अपने तरीके से करती है, जैसे कोई बच्चा Grandma की recipe को थोड़े बदलाव के साथ पकाए। Parent को virtual शब्द से कहना होगा कि method बदली जा सकती है।
In this page:
Syntax
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- base method में
virtualभूल जाना, जिससेoverrideकी अनुमति नहीं मिलती। - derived method में
overrideभूल जाना, जो override करने के बजाय एक hiding warning बनाता है। - किसी overriding method का return type या parameters बदलना, जो एक compile error है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: