কম্পিউটার টিউটোরিয়াল

C#-এ ইন্টারফেস এবং ইনহেরিটেন্স (Inheritance)

ইন্টারফেস (Interface)

একটি ইন্টারফেস হলো একটি সিনট্যাকটিক্যাল কনট্র্যাক্ট যা ইন্টারফেস ইনহেরিট करनेवाले সকল ক্লাসকে মানতে হয়। ইন্টারফেস কনট্র্যাক্টের 'কী' (what) অংশ সংজ্ঞায়িত করে এবং ডেরাইভড ক্লাস 'কীভাবে' (how) অংশ সংজ্ঞায়িত করে।

ইন্টারফেস উদাহরণ

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System; 
namespace InterfaceApplication { 
    public interface ITransactions { 
        void showTransaction(); 
        double getAmount(); 
    } 
    public class Transaction : ITransactions { 
        private string tCode; 
        private string date; 
        private double amount; 
        public Transaction() { 
            tCode = ""; 
            date = ""; 
            amount = 0.0; 
        } 
        public Transaction(string c, string d, double a) { 
            tCode = c; 
            date = d; 
            amount = a; 
        } 
        public double getAmount() { return amount; } 
        public void showTransaction() { 
            Console.WriteLine("Transaction: {0}", tCode); 
            Console.WriteLine("Date: {0}", date); 
            Console.WriteLine("Amount: {0}", getAmount()); 
        } 
    } 
    class Tester { 
        static void Main(string[] args) { 
            Transaction t1 = new Transaction("001", "8/10/2012", 78900.00); 
            Transaction t2 = new Transaction("002", "9/10/2012", 451900.00); 
            t1.showTransaction(); 
            t2.showTransaction(); 
            Console.ReadKey(); 
        } 
    } 
}

আউটপুট

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

ইনহেরিটেন্স (Inheritance)

ইনহেরিটেন্স আমাদের একটি ক্লাসকে অন্য ক্লাসের মাধ্যমে সংজ্ঞায়িত করতে দেয়, যা অ্যাপ্লিকেশন তৈরি ও রক্ষণাবেক্ষণ সহজ করে। এটি কোড রিইউজ (code reuse) সুযোগ দেয় এবং বাস্তবায়ন সময় কমায়।

ইনহেরিটেন্স IS-A সম্পর্ক বাস্তবায়ন করে। উদাহরণ: ম্যামেল (mammal) IS-A অ্যানিমাল (animal), ডগ (dog) IS-A ম্যামেল, সুতরাং ডগ IS-A অ্যানিমালও।

ইনহেরিটেন্স উদাহরণ

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
  1. ইন্টারফেস এবং সার্ভিস বলতে কী বোঝায়?

  2. জাভাতে ইনহেরিটেন্স এবং কম্পোজিশনের পার্থক্য

  3. পাইথনে ৩ ও ৭ এর গুণিতকের যোগফল দিয়ে সংখ্যা তৈরি করা সম্ভব কিনা

  4. পাইথনে ক্লাস এবং ইনহেরিটেন্সের পরিচিতি