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{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:-
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:
Post a Comment
Post a Comment