Thursday, September 5, 2013

INTRODUCTION TO INHERITANCE IN JAVA

INHERITANCE

The concept of inheritance much more similar as in the real world itself. Inheritance means the passing of similar traits and features from older ones to younger ones. This same concept is taken from the real life and applied in the object oriented principles of programming languages too.
Necessity is the mother of invention fits better here, as in the earlier days of programming when there was no inheritance at all, programmers have to rewrite whole of the complex methods again and again which they wrote earlier in some other programme. They felt very exhausted writing these common but complex methods again and again whenever they have to write new code. They started to think of ways :
1. what if they introduce some way , by which they could be able to use previously written methods from previously written codes.
2. what if they find a solution to introduce a link among different piece of codes.
These necessities gave birth to the concept of inheritance.
With the advent of inheritance , the above problems found solutions. Now, if some code has to re-use the previously written methods and fields in some other code, it just inherits all of them by just writing a keyword 'extends'.

The programming life has become much easier with the introduction of inheritance. Java allows only single inheritance, though some other programming languages allow multiple inheritance too(e.g. C++ ).

Single inheritance

when a class can inherit only one other class i.e. having only one parent class. This kind inheritance is called Single inheritance.

Multiple inheritance

when a class inherits more than one class i.e. having multiple parent classes. This kind of inheritance is calles Multiple inheritance.

e.g.

public class Vehicle {
int numOfWheels;
int topSpeed;
int engineCapacity;
int gears;
void shiftGear(int gear) {
/ / / / /
/ / /
}
void speedUpBy(int mark){
/ / / / /
 / / /
}
}

public class Motorbike extends Vehicle{
int seats;
int mileage;
void start() {
/ / / /
/ / /
}
void stop() {
/ / / /
/ / /
}
}

We can clearly see in above example, that Motorbike class extends Vehicle class in its first statement, by doing this, the Motorbike class is able to inherit all the features of Vehicle class, without having it to write all those methods again. This is how inheritance makes the coding easier than before.
Here the Motorbike class is called subclass. 
The Vehicle class is called superclass.


SUB-CLASS

The class that is derived from the another class is called as sub-class (also called as child-class, derived class or extended class).

SUPER-CLASS

The class from which sub-class is derived is called as super-class ( also called as a base-class or a parent class ).


NOTE : there exist

No comments:

Post a Comment