1. What is Inheritance in Java:
In Java, Inheritance is one of the core concepts of Object-Oriented Programming (OOP). It allows one class to acquire the properties and methods of another class, promoting code reusability and better organization.
Syntax of Inheritance:
class Parent {
** // properties and methods**
}
class Child extends Parent {
**// additional features**
}
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); **// inherited method**
d.bark(); **// own method**
}
}
Types of Inheritance in Java:
- Single Inheritance
One parent → One child
- Multilevel Inheritance
Grandparent → Parent → Child
- Hierarchical Inheritance
One parent → Multiple children
Java does not support multiple inheritance using classes (to avoid complexity)
Advantages of Inheritance:
Code reusability
Reduces redundancy
Improves maintainability
Supports method overriding
Top comments (0)