ইনহেরিটেন্সের মাধ্যমে আপনি একটি ক্লাসকে অন্য একটি ক্লাসের মাধ্যমে ডিফাইন করতে পারেন, যা অ্যাপ্লিকেশন তৈরি এবং মেইনটেইন করাকে সহজ করে তোলে। এতে কোড ফাংশনালিটি রিয়োজ করার সুযোগ করে দেয় এবং ইমপ্লিমেন্টেশন টাইম দ্রুত হয়।
ইনহেরিটেন্স বেস ক্লাস এবং ডেরাইভড ক্লাস কনসেপ্টের ওপর ভিত্তি করে। একটি ক্লাস একাধিক ক্লাস বা ইন্টারফেস থেকে ডেরাইভ করা যায়, অর্থাৎ সেটি একাধিক বেস ক্লাস বা ইন্টারফেস থেকে ডেটা এবং ফাংশন ইনহেরিট করতে পারে।
বেস এবং ডেরাইভড ক্লাসের উদাহরণ দেখা যাক। এখানে Shape হলো বেস ক্লাস এবং Rectangle হলো ডেরাইভড ক্লাস:
class Rectangle : Shape {
// methods
}
ইনহেরিটেন্সে বেস ক্লাস এবং ডেরাইভড ক্লাস কীভাবে কাজ করে তা দেখানোর উদাহরণ:
উদাহরণ
using System;
namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle : Shape {
public int getArea() {
return (width * height);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// অবজেক্টের এরিয়া প্রিন্ট
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
আউটপুট
Total area: 35