Inheritance Java की Object-Oriented Programming (OOP) की एक खास feature है। इससे एक class दूसरी class की properties और methods को reuse कर सकती है।
जैसे बच्चा अपने माता-पिता से कुछ गुणों को विरासत में लेता है, वैसे ही Java में एक class दूसरी class से features inherit कर सकती है।
class Parent {
void showMessage() {
System.out.println("I am Parent Class");
}
}
class Child extends Parent {
void display() {
System.out.println("I am Child Class");
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.showMessage(); // Inherited method
obj.display(); // Child's method
}
}
extends
– subclass को superclass से जोड़ने के लिएsuper
– parent class के constructor या method को access करने के लिएType | Description |
---|---|
Single Inheritance | एक class दूसरी class से inherit करती है |
Multilevel Inheritance | एक class दूसरी class से, और वो class एक और class से inherit करती है |
Hierarchical Inheritance | एक class से कई subclasses inherit करते हैं |
Multiple Inheritance | Java में class से multiple inheritance सीधे possible नहीं है, लेकिन interfaces से हो सकता है |
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Puppy is weeping");
}
}
public class Test {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // from Animal
p.bark(); // from Dog
p.weep(); // from Puppy
}
}
Inheritance एक powerful concept है जो Java में कोड को छोटा, reusable और maintainable बनाता है। यह OOPs की base pillars में से एक है।