Wednesday, July 1, 2009

Why code reuse is an exclusive feature of Inheritance??

The Inheritance in Java can have two ways of implementation:-

1.Code Reuse
2.Polymorphism

Since Inheritance is the core concept of OO programming ,thus it is must to understand "Code Reuse".Code Reuse lets a programmer to use the code of more generic super-class into subclasses.You need not write extra code for any of your method if the behaviour is common to both super class and subclass.As we know Super classes are more general whereas the subclasses are more of a special kind,that is why the general methods and variables are defined in super classes.Whereas a subclass can either extend the functionality or use whatever given in super class.

Code Reuse Example:-

class Car{
public void color(){

System.out.println("Color of your car is: Black");
}
}

Public class Subaru extends Car{
public void accelerate(){

System.out.println("Top speed of Subaru is 120 mph");
}
public static void main(String a[]){
Subaru sbr=new Subaru();
sbr.color();
sbr.accelerate();
}
}

Output :-
Color of your car is: Black
Top speed of Subaru is 120 mph

Here you can see that class Subaru extends Car thus it Inherits the color() method of Subaru.Also it can also add its own method as accelerate() which is only Subaru specific that its top speed is 120mph.That is every can have its own color and its generic for every car thus every car extending the Car class need not reimplement the color() method.

Home

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP