Monday, 16 April 2012

Inheritance in Java

Inheritance 

is one of the principle features of Object Oriented Programming Languages

It is a phenomenon of acquiring the properties of one object by another. It is a process in which the properties of an object can be shared by other objects.

Java supports inheritance by means of a key word "Extends". The key word can be used to extend the properties of one object by another.

Syntax: class class_name extends class_name(parent){

                }


Example: class Dog extends Animal{

                   }


Inheritance has many types : It may be a Single Level, Multi Level or a Multiple Level

but Java doesn't support multiple inheritance directly, instead we can have multiple inheritance in our program by use of Abstract Class and Interface.

For example consider the family of Animal:




The Animal class is extended by the classes Duck and Dog....

When these classes are held together,

they form a Class Hierarchy.. i.e., an Inheritance Tree.

The class at the parent position is the Super Class 


The Child Class is called Sub Class which extends the properties of Super class.

One of the Application of Inheritance is the method overriding.

Method Overriding:

It is a process in which two methods have the same name and signature in two classes which are inherited.

It can be simplified as the method in the parent class is used as it is in the child class but the body differs...

Let me explain with an example:

Consider two classes A and B which are parent and child to one another...

if there is a method add(int a,int b) in class A and class B is the sub class of A then the method in A is override in B as....

class A{

              int addNumber(int a,int b){
                                           return a+b;
              }
}

class B extends A{

             int addNumber(int a,int b){                //Observe the name and the parameters
                                         int x=a++;
                                         int y=b++;
                    return x+y;
             }
}


class Demo{
      public static void main(String args[ ]){
             new A().addNumber(5,6);                     // This invokes method in class A 
             new B().addNumber(5,6);                     // This invokes method in class B
      }
}

This feature is one of the useful weapons to promote abstraction...

The Super Class will contain only the method declarations and the Sub Classes override them and contain the definitions. 








No comments:

Post a Comment