This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes doubt in interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "doubt in interface" Watch "doubt in interface" New topic

doubt in interface

anita mitra

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

Joined: Oct 02, 2003
Posts: 11957

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.


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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
anita mitra

Joined: Jul 03, 2009
Posts: 21

I agree. Here's the link:
subject: doubt in interface
It's not a secret anymore!