Multiple Bounds জাভার জেনেরিক্সের একটি বৈশিষ্ট্য যা একটি টাইপ প্যারামিটারকে একাধিক শর্তে সীমাবদ্ধ করতে দেয়। এটি extends কীওয়ার্ড ব্যবহার করে প্রয়োগ করা হয় এবং একটি ক্লাস বা ইন্টারফেসের সংমিশ্রণকে নির্দেশ করে।
Multiple Bounds এর সংজ্ঞা
- একটি টাইপ প্যারামিটার একইসঙ্গে একটি ক্লাস এবং একাধিক ইন্টারফেস প্রসারিত করতে পারে।
সিনট্যাক্স:
<T extends ClassName & Interface1 & Interface2>- প্রথমে সর্বদা একটি ক্লাস থাকতে হবে (যদি প্রয়োজন হয়), এবং তারপর ইন্টারফেস থাকতে পারে।
Multiple Bounds এর উদাহরণ
1. ক্লাস এবং ইন্টারফেসের সংমিশ্রণ
interface Drivable {
void drive();
}
interface Maintainable {
void maintain();
}
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
public class MultiBoundExample<T extends Vehicle & Drivable & Maintainable> {
private T obj;
public MultiBoundExample(T obj) {
this.obj = obj;
}
public void operate() {
obj.start();
obj.drive();
obj.maintain();
}
}
ব্যবহারের উদাহরণ:
class Car extends Vehicle implements Drivable, Maintainable {
@Override
public void drive() {
System.out.println("Car is driving");
}
@Override
public void maintain() {
System.out.println("Car is being maintained");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
MultiBoundExample<Car> example = new MultiBoundExample<>(car);
example.operate();
}
}
আউটপুট:
Vehicle started
Car is driving
Car is being maintained
2. শুধুমাত্র ইন্টারফেসের সংমিশ্রণ
interface Readable {
void read();
}
interface Writable {
void write();
}
class MultiBoundInterfaceExample<T extends Readable & Writable> {
private T obj;
public MultiBoundInterfaceExample(T obj) {
this.obj = obj;
}
public void process() {
obj.read();
obj.write();
}
}
ব্যবহারের উদাহরণ:
class Document implements Readable, Writable {
@Override
public void read() {
System.out.println("Reading the document");
}
@Override
public void write() {
System.out.println("Writing to the document");
}
}
public class Main {
public static void main(String[] args) {
Document doc = new Document();
MultiBoundInterfaceExample<Document> example = new MultiBoundInterfaceExample<>(doc);
example.process();
}
}
আউটপুট:
Reading the document
Writing to the document
নিয়ম এবং সীমাবদ্ধতা
ক্লাস সর্বদা প্রথমে থাকতে হবে:
<T extends Class & Interface1 & Interface2>ভুল:
<T extends Interface1 & Class>।একই সময়ে শুধুমাত্র একটি ক্লাস থাকতে পারে: একটি টাইপ প্যারামিটার একাধিক ক্লাস প্রসারিত করতে পারে না।
ভুল:
<T extends Class1 & Class2 & Interface>- অজানা টাইপের জন্য কাজ করে না: Multiple Bounds শুধুমাত্র টাইপ প্যারামিটার ডিফাইন করার সময় ব্যবহার করা যায়।
Multiple Bounds এর সুবিধা
- টাইপ-সেফটি: টাইপ প্যারামিটার নির্দিষ্ট ক্লাস এবং ইন্টারফেসে সীমাবদ্ধ করা যায়।
- ফ্লেক্সিবিলিটি: একই টাইপ প্যারামিটারের মাধ্যমে একাধিক কার্যকরীতা অর্জন করা যায়।
- রিডেবল এবং কার্যকরী কোড: কোড পরিষ্কার এবং সহজে ব্যবস্থাপনা করা যায়।
Multiple Bounds জেনেরিক্স ব্যবহার করে টাইপ প্যারামিটারগুলিকে আরো কার্যকরী এবং শক্তিশালী করে। এটি জাভায় টাইপ সেফ এবং রিইউজেবল কোড লেখার একটি উন্নত পদ্ধতি।
Content added By
Read more