*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "doubt in interface" Watch "doubt in interface" New topic
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: 11169
    
  16

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.


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

Joined: Jul 03, 2009
Posts: 21

thanks
 
wood burning stoves
 
subject: doubt in interface
 
Similar Threads
Memory Allocation and Benifit of an Interface Referance Variable over class referance
Confused about Dan's exam...
execution program
Inner class question from Dan's exam
Use Of Interface