WHAT IS INHERITANCE IN JAVA?

Royce Roy

Total Post:51

Points:255
Posted by  Royce Roy
Java 
 641  View(s)
Ratings:
Rate this:
  1. Mayank Tripathi

    Post:807

    Points:4035
    What is Inheritance in java?

    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. }  

    Output:

    Programmer salary is:40000.0
    Bonus of programmer is:10000

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!