Inheritance
Inheritance is a mechanism in which one class (say child class or derived class) derives the properties i.e. methods and fields of another class(say a parent or base class) including itself.
Use of Inheritance:
Use of Inheritance:
- Code Reusability: Inheritance is mostly used to increase the reusability(using the same piece of code oftentimes).
- Efficient Program Structure: Simplifies code maintenance and modification.
- Supports Runtime Polymorphism: Helps in method overriding and achieving dynamic method dispatch.
Syntax:
class child_class-name extends parent_class-name
{
// your code
}
Example:
package quipohouse;
class Parent{
int a=10;
void parentMethod() {
System.out.println("Inside Parent Class");
}
}
class Child extends Parent{
int b=10;
void childMethod() {
System.out.println("Inside Child Class");
}
public static void main(String[] args) {
Child c=new Child();
c.childMethod(); //child method is invoked
c.parentMethod(); //parent method is invoked
System.out.println("field of child class-"+c.b); //child class field
System.out.println("field of parent class-"+c.a); //parent class field
}
}
Output:
Inside Child Class
Inside Parent Class
field of child class-10
field of parent class-10
Explanation:
- The Child class inherits the properties of the Parent class.
- The object of Child class (c) is able to access both child and parent methods & fields.
- This shows how inheritance allows reusability of code.