01. What is the Inheritance?
Child object behaving as a parent object.
keyword : extends
02. Why use inheritance?
Code Reusability: You can reuse attributes and methods of an existing class when creating a new class.
Example:
Class BMWV1{
color=Red
speed=100
}
Class BMWV2 extends BMWV1{
speed=200
}
Extensibility: You can extend the functionalities of a class in derived classes.
*03. What are the types of inheritance?
*
1. Single inheritance
2. Hierarchical inheritance
3. Multilevel inheritance
4. Multiple inheritance
Note:
- No need to call the object method without the main method variable for the parent.
- We can directly use the variable to call the child's main method.
- We can't use the Boolean method in inheritance.
04. What is Single inheritance?
-one parent class & one child class.
-We can access the methods and variables in the parent class in the child class.
-We can access the methods and variables in the child class also.
05. What is Hierarchical inheritance?
-One parent class & two child classes.
-We can access the methods and variables in the parent class in the child classes 1 & 2.
-We can access the methods and variables in the child class also.
-We can access the methods and variables in the child class 1 also.
06. What is the Multi-level inheritance?
-We can access the methods and variables in the child class from the child class 2.
-We can access the methods and variables in the parent class in the child classes 1 & 2.
-We can access the methods and variables in the child class also.
-We can access the methods and variables in the child class 1 also.
07. What is Multiple inheritance?
-We can't extend the double class (EX, Mom, Dad)
-Multiple inheritance can't be supported in Java.
**Reason:
Because the same or different "Main Method name", we can't call the child class.
EXample:
Public void work(){
syso .p ("Dad work")}
Public void work(){
syso .p ("Mom work")}
08. How to use the inheritance?
To use inheritance in Java, you follow a few simple steps to create a parent-child relationship between classes, sharing code and extending functionality.
1. Define a Superclass (Parent)
Create a class with common properties and methods that you want other classes to inherit.
2. Define a Subclass using extends
Use the extends keyword to create another class that inherits from the superclass.
3. Use Inherited Methods and Fields
Create an object of the subclass to access both its own and inherited superclass methods.
09. Where do we use the inheritance?
Inheritance is used in Java wherever there is an is-a relationship between objects. Here are common scenarios and examples where inheritance is applied.
Modelling Real-World Hierarchies
Example: Animals, Vehicles, People.
The base class could be Animal, and specific animals, such as Dog, Cat, or Cow, would extend it and implement their unique behaviours.
Similarly, Vehicle can be a superclass, with subclasses like Car and Bus representing more specific types
Top comments (0)