Many people get confused with what is interface, many treat it as a class, some treat as a class which has only abstract method, which is correct though.
I give you some real time example to define interface.
Interface is basically a contract which any class signs when it implements that.
for example, when you join a company, you have to sign the contract after which only you will be treated as infosysian,wiporian or what ever it is.
so what is there in contract, its just the rules which is going to make you infosysian. Rules are declared there, not defined.
eg.
1. your working time will be 9-6.
2. your attire should be formal.
3.your salary will be this much etc...
so you see that all the rules are only declared in contract, which will be implemented by you when you sign it.You will be bound to implement all rules, declared there thats what signing of contract says.
Interface is also an contract which says, if you implement me, you have to implement all the rules declared inside.
We use interface for necessery and uncommon behaviour.
Neccessery because every one has to defined all the methods declared inside interface.
uncommon because each class might have there own definition.
for example.
if Human is a class then common and uncommon behaviour would be.
common.
doSleep()
doEat()
doBreath()
uncommon;
doTalk() --> he might be dumb
doSee() --> might be blind
see here you can see that its good to put uncommon behavoiur into interface as evey human has to deifne those methods but difinition might be diff.
lets see the code.
public interface Human{
public boolean doSee();
public boolean doSpeak();
}
public class Rakesh implements Human{
public boolean doSee(){
return true;
}
public boolean peak(){
return false;
}
}
Subscribe to:
Post Comments (Atom)
 
 
You are explaining what is an interface. Thats ok.
ReplyDeleteWhat is the use of interface, why it came into picture and how it is being useful in application development or software development?
best use is to achieve plymorphism...
ReplyDeleteinterface is usefull in hiding the implementaion as well...
factory,abstract factory and many more design patterns are there which are been developed based on interface...
if you notice all new and latest version of java is having more no of interfaces than classes.
more over no one force you to use interface.. but its your own requirement and understanding how efficiently you can use... best example...
ReplyDeletesuppose you have to build an applicaton which should support all data bases... like orace, db2,sql server, my sql and etc...
so now you know that what ever data base it is but methods are going to be same but implementation might be diff... so best way is put all required method in an interface... let classes implement it and define the methods in its own way... this is simple example.. there aer many more.. hope this helps..