ইনহেরিটেন্স (Inheritance) হল দুটি ক্লাসের মধ্যে একটি সম্পর্ক যেখানে একটি ক্লাস অন্য ক্লাসের প্রোপার্টি ইনহেরিট করে। এই সম্পর্ক `extends` কীওয়ার্ড দিয়ে ডিফাইন করা হয়:
public class A extends B { }
যে ক্লাস ইনহেরিট করে সেটিকে সাব ক্লাস (sub class) বা চাইল্ড ক্লাস (child class) বলা হয় এবং যার প্রোপার্টি ইনহেরিট করা হয় সেটিকে সুপার ক্লাস (super class) বা প্যারেন্ট ক্লাস (parent class) বলা হয়।
ইনহেরিটেন্সে সুপার ক্লাসের মেম্বারগুলোর একটি কপি সাব ক্লাস অবজেক্টে তৈরি হয়। তাই সাব ক্লাস অবজেক্ট ব্যবহার করে দুটি ক্লাসের মেম্বার অ্যাক্সেস করা যায়।
সাব ক্লাস ভেরিয়েবলকে সুপার ক্লাস টাইপে কনভার্ট করা
আপনি সরাসরি একটি সাব ক্লাস ভেরিয়েবল (ভ্যালু) একটি সুপার ভেরিয়েবলে অ্যাসাইন করতে পারেন। সংক্ষেপে, সুপার ক্লাস রেফারেন্স ভেরিয়েবল সাব ক্লাস অবজেক্ট ধারণ করতে পারে। কিন্তু এই রেফারেন্স ব্যবহার করে আপনি শুধু সুপার ক্লাসের মেম্বার অ্যাক্সেস করতে পারবেন, যদি আপনি সাব ক্লাস মেম্বার অ্যাক্সেস করার চেষ্টা করেন তবে কম্পাইল টাইম এরর জেনারেট হবে।
উদাহরণ ১
class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
public class Sample extends Person {
public String branch;
public int Student_id;
public Sample(String name, int age, String branch, int Student_id) {
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: " + super.name);
System.out.println("Age: " + super.age);
System.out.println("Branch: " + this.branch);
System.out.println("Student ID: " + this.Student_id);
}
public static void main(String[] args) {
Person person = new Person("Krishna", 20);
// সাব ক্লাস ভেরিয়েবলকে সুপার ক্লাস টাইপে কনভার্ট করা
Sample sample = new Sample("Krishna", 20, "IT", 1256);
person = sample;
person.displayPerson();
}
}
আউটপুট
Data of the Person class: Name: Krishna Age: 20
উদাহরণ ২
class Super {
public Super() {
System.out.println("Constructor of the Super class");
}
public void superMethod() {
System.out.println("Method of the super class");
}
}
public class Test extends Super {
public Test() {
System.out.println("Constructor of the sub class");
}
public void subMethod() {
System.out.println("Method of the sub class");
}
public static void main(String[] args) {
Super obj = new Test();
obj.superMethod();
}
}
আউটপুট
Constructor of the Super class Constructor of the sub class Method of the super class