Tuesday 8 March 2016

Inheritance and its purpose

Inheritance concept allows code defined in one class to be re-used in other classes. Or it can be said that Inheritance is the property by virtue of which sub-class can inherit all the property (except restricted ones) of its super-class.
If a class wants to inherit any other class then it must use keyword extends .
For example,

class Car{                                   //Car is superclass.
     int wheels = 4;
     int maxSpeed = 200;
     public void cost(){.....}
     public void features(){.....}

Now suppose car manufacturer of Audi is planning to launch another car model 'Zoro'. So this model must inherit the core properties that a car possess.

class AudiZoro extends Car{    //AudiZoro is subclass that inherits(or extends) super class Car


Once you extend Car then what are the benefits that you get :

  • You can use all the variables and methods in the superclass Car in the subclass AudiZoro. So Inheritance provides scope for code re-usability.
  • You can override any method say cost or features to define it according to your own wish. So Inheritance provides scope for Polymorphism.

No comments:

Post a Comment

If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.