Home > DeveloperSection > Interviews > What is Inheritance in java?

Posted on    March-28-2015 12:06 AM

 Java Java 
 1 Answer(s)
  412  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Posted on    March-28-2015 12:47 AM

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also
Inheritance represents the IS-A relationship, also known as parent-child relationship

Why use inheritance in java
  1. For Method Overriding (so runtime polymorphism can be achieved).
  2. For Code Reusability.
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

  1. class Employee{  
  1.  float salary=40000;  
  1. }  
  1. class Programmer extends Employee{  
  1.  int bonus=10000;  
  1.  public static void main(String args[]){  
  1.    Programmer p=new Programmer();  
  1.    System.out.println("Programmer salary is:"+p.salary);  
  1.    System.out.println("Bonus of Programmer is:"+p.bonus);  
  1. }  


Programmer salary is:40000.0
Bonus of programmer is:10000

Don't want to miss updates? Please click the below button!

Follow MindStick