Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in interface

 
anita mitra
Greenhorn
Posts: 21
Eclipse IDE MySQL Database Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12146
30
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
anita mitra
Greenhorn
Posts: 21
Eclipse IDE MySQL Database Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic