Interview question
What is Inheritance and how does it work in Java? Java में Inheritance क्या है और यह कैसे काम करता है?
Answer
Inheritance is a mechanism where a child class inherits properties and methods from a parent class. It promotes code reusability and establishes a relationship between classes.
// Parent Class
public class Vehicle {
protected String color;
protected int speed;
public void start() {
System.out.println('Vehicle started');
}
public void stop() {
System.out.println('Vehicle stopped');
}
}
// Child Class (inherits from Vehicle)
public class Car extends Vehicle {
private int numberOfDoors;
public Car(String color, int speed, int doors) {
this.color = color;
this.speed = speed;
this.numberOfDoors = doors;
}
// Overriding parent method
@Override
public void start() {
System.out.println('Car engine started');
}
public void displayDoors() {
System.out.println('Number of doors: ' + numberOfDoors);
}
}
// Another Child Class
public class Bike extends Vehicle {
private boolean hasHelmet;
public void wheelie() {
System.out.println('Bike doing wheelie');
}
}
// Using Inheritance
public class Main {
public static void main(String[] args) {
Car car = new Car('Red', 100, 4);
car.start(); // Calls overridden method
car.displayDoors();
Bike bike = new Bike();
bike.start(); // Calls parent method
bike.wheelie();
}
}
// Types of Inheritance:
// 1. Single Inheritance: Child extends one Parent
// 2. Multilevel Inheritance: A extends B, B extends C
// 3. Hierarchical Inheritance: Multiple children extend one parent
// 4. Multiple Inheritance: Not directly supported (use interfaces)Inheritance: Child class parent class से properties inherit करता है।
Syntax: public class Child extends Parent {}
Benefits:
1. Code reusability
2. Method overriding
3. Polymorphism supportWas this answer clear?