Inheritance in Java
1. Definition of Inheritance
- Inheritance is a mechanism in Java where a new class (subclass) acquires properties and
behaviors of an existing class (superclass).
2. Types of Inheritance in Java:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- (Java does not support multiple inheritance with classes but supports it via interfaces)
3. Syntax and Example:
```java
class Parent {
int a = 10;
void show() {
[Link]("This is parent class");
}
}
class Child extends Parent {
void display() {
[Link]("This is child class, value of a: " + a);
}
}
public class Main {
public static void main(String args[]) {
Child obj = new Child();
[Link]();
[Link]();
}
}
```
4. Super and Subclass:
- The superclass is the parent class that passes its properties to the child.
- The subclass is the child class that inherits from the parent class.
5. Method Overriding:
- When a subclass provides its own implementation of a method present in the superclass.
6. 'super' Keyword:
- Used to call the parent class constructor or method.
7. 'final' Keyword with Inheritance:
- If a class is declared final, it cannot be inherited.
8. Advantages of Inheritance:
- Code reusability
- Improved maintainability
- Less redundancy