| Author |
doubt in interface
|
anita mitra
Greenhorn
Joined: Jul 03, 2009
Posts: 21
|
|
this is the program
public interface Addition{
public int add(int a,int b);
}
suppose there is a class which implements this interface
public class x implements Addition{
public int add(int a,int b){
int c=a+b;
return c;
}
}
another class calls add method by
Addition y= new x();
int z=y.add(5,6);
why we are creating interface type of reference to x object?
why can't we use x y=new x();
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9940
|
|
You could...but then you are locked into it being an x.
Think about large software development groups. they may be broken down into teams. Team A want to use a widget. Team B will write the widget. Team B could say "here is a static method that will return a widget of type x".
Team A will call that method to get an object they will use.
Now, if Team A writes their code to always expect an object of type x, everything is fine. But suppose in a year, Team B comes up with something that works better, faster, and uses less memory. They can now say "We will give you a widget of type y". Team A has to go through every single line of code and look for what needs to be changed.
HOWEVER...
If Team B has said "we will return something that implements the Addition interface"...
Team A writes their code with references to have reference types. Then, when team B comes up with their new widget, Team A doesn't have to change their code since they will still be getting something that implements the Addition interface. The actual object type doesn't matter.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
anita mitra
Greenhorn
Joined: Jul 03, 2009
Posts: 21
|
|
thanks
|
 |
 |
|
|
subject: doubt in interface
|
|
|