ওভাররাইডিং (Overriding)
ওভাররাইডিং-এ, আপনি সাবক্লাস টাইপের জন্য নির্দিষ্ট একটি বিহেভিয়ার ডিফাইন করেন, অর্থাৎ একটি সাবক্লাস প্যারেন্ট ক্লাসের মেথডটি নিজের প্রয়োজন অনুযায়ী ইমপ্লিমেন্ট করতে পারে।
অ্যাবস্ট্র্যাক্ট ক্লাস ব্যবহার করে ওভাররাইডিং ইমপ্লিমেন্ট করার উদাহরণ:
উদাহরণ
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle(int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area() {
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}", a);
Console.ReadKey();
}
}
}
শ্যাডোইং (Shadowing)
শ্যাডোইংকে মেথড হাইডিং (Method Hiding) ও বলা হয়। প্যারেন্ট ক্লাসের মেথড চাইল্ড ক্লাসে override কীওয়ার্ড ছাড়া উপলব্ধ থাকে শ্যাডোইং-এ। চাইল্ড ক্লাসের সেই ফাংশনটির নিজস্ব ভার্সন থাকে।
শ্যাডোইং করার জন্য এবং বেস ক্লাস ফাংশন নিজস্ব ভার্সন তৈরি করতে new কীওয়ার্ড ব্যবহার করুন।
উদাহরণ
using System;
using System.Collections.Generic;
class Demo {
public class Parent {
public string Display() {
return "Parent Class!";
}
}
public class Child : Parent {
public new string Display() {
return "Child Class!";
}
}
static void Main(String[] args) {
Child child = new Child();
Console.WriteLine(child.Display());
}
}