Java Inheritance

June 22,2016

Today i have learnt about java inheritance and how it is used.Also i have come to know the use of ‘this’ and ‘super’ keyword.

Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.
    1. class Subclass-name extends Superclass-name
    2. {
    3. //methods and fields
    4. }

    extends Keyword

    extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.

    Syntax

    class Super {
       .....
       .....
    }
    class Sub extends Super {
       .....
       .....
    }
    
    

    Types of inheritance in java

    On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.typesofinheritance

    The super keyword

    The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used.

    • It is used to differentiate the members of superclass from the members of subclass, if they have same names.
    • It is used to invoke the superclass constructor from subclass.

    Usage of java this keyword

    Here is given the 6 usage of java this keyword.

    1. this keyword can be used to refer current class instance variable.
    2. this() can be used to invoke current class constructor.
    3. this keyword can be used to invoke current class method (implicitly)
    4. this can be passed as an argument in the method call.
    5. this can be passed as argument in the constructor call.
    6. this keyword can also be used to return the current class instance.

 

 

Leave a comment