Inheritance
What is 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.
Need of Inheritance
- Inheritance is mostly used to increase the reusability(using the same piece of code oftentimes) of code which makes the program efficient.
- Also to achieve runtime polymorphism(you will read further in detail)
Implementation of Inheritance
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
As in the above program, we can see then how the child class object is invoked by both the methods and fields of the parent class including itself.