Você está na página 1de 4

7/16/2016

JavaInterfaces
We are hiring

JavaInterfaces
Advertisements

PreviousPage

NextPage

An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods. A class implements an interface,
therebyinheritingtheabstractmethodsoftheinterface.
Alongwithabstractmethodsaninterfacemayalsocontainconstants,defaultmethods,staticmethods,andnestedtypes.Methodbodies
existonlyfordefaultmethodsandstaticmethods.
Writinganinterfaceissimilartowritingaclass.Butaclassdescribestheattributesandbehavioursofanobject.Andaninterfacecontains
behavioursthataclassimplements.
Unlesstheclassthatimplementstheinterfaceisabstract,allthemethodsoftheinterfaceneedtobedefinedintheclass.
Aninterfaceissimilartoaclassinthefollowingways:
Aninterfacecancontainanynumberofmethods.
Aninterfaceiswritteninafilewitha.javaextension,withthenameoftheinterfacematchingthenameofthefile.
Thebytecodeofaninterfaceappearsina.classfile.
Interfacesappearinpackages,andtheircorrespondingbytecodefilemustbeinadirectorystructurethatmatchesthepackage
name.
However,aninterfaceisdifferentfromaclassinseveralways,including:
Youcannotinstantiateaninterface.
Aninterfacedoesnotcontainanyconstructors.
Allofthemethodsinaninterfaceareabstract.
Aninterfacecannotcontaininstancefields.Theonlyfieldsthatcanappearinaninterfacemustbedeclaredbothstaticandfinal.
Aninterfaceisnotextendedbyaclassitisimplementedbyaclass.
Aninterfacecanextendmultipleinterfaces.

DeclaringInterfaces:
Theinterfacekeywordisusedtodeclareaninterface.Hereisasimpleexampletodeclareaninterface:

Example:
Belowgivenisanexampleofaninterface:
/*Filename:NameOfInterface.java*/
importjava.lang.*;
//Anynumberofimportstatements
publicinterfaceNameOfInterface
{
//Anynumberoffinal,staticfields
//Anynumberofabstractmethoddeclarations\
}

Interfaceshavethefollowingproperties:

http://www.tutorialspoint.com/java/java_interfaces.htm

1/4

7/16/2016

JavaInterfaces
Aninterfaceisimplicitlyabstract.Youdonotneedtousetheabstractkeywordwhiledeclaringaninterface.
Eachmethodinaninterfaceisalsoimplicitlyabstract,sotheabstractkeywordisnotneeded.
Methodsinaninterfaceareimplicitlypublic.

Example:
/*Filename:Animal.java*/
interfaceAnimal{
publicvoideat();
publicvoidtravel();
}

ImplementingInterfaces:
Whenaclassimplementsaninterface,youcanthinkoftheclassassigningacontract,agreeingtoperformthespecificbehaviorsofthe
interface.Ifaclassdoesnotperformallthebehaviorsoftheinterface,theclassmustdeclareitselfasabstract.
Aclassusestheimplementskeywordtoimplementaninterface.Theimplementskeywordappearsintheclassdeclarationfollowingthe
extendsportionofthedeclaration.
/*Filename:MammalInt.java*/
publicclassMammalIntimplementsAnimal{
publicvoideat(){
System.out.println("Mammaleats");
}
publicvoidtravel(){
System.out.println("Mammaltravels");
}
publicintnoOfLegs(){
return0;
}
publicstaticvoidmain(Stringargs[]){
MammalIntm=newMammalInt();
m.eat();
m.travel();
}
}

Thiswouldproducethefollowingresult:
Mammaleats
Mammaltravels

Whenoverridingmethodsdefinedininterfacesthereareseveralrulestobefollowed:
Checkedexceptionsshouldnotbedeclaredonimplementationmethodsotherthantheonesdeclaredbytheinterfacemethodor
subclassesofthosedeclaredbytheinterfacemethod.
Thesignatureoftheinterfacemethodandthesamereturntypeorsubtypeshouldbemaintainedwhenoverridingthemethods.
Animplementationclassitselfcanbeabstractandifsointerfacemethodsneednotbeimplemented.
Whenimplementationinterfacesthereareseveralrules:
Aclasscanimplementmorethanoneinterfaceatatime.
Aclasscanextendonlyoneclass,butimplementmanyinterfaces.
Aninterfacecanextendanotherinterface,similarlytothewaythataclasscanextendanotherclass.

ExtendingInterfaces:
Aninterfacecanextendanotherinterface,similarlytothewaythataclasscanextendanotherclass.Theextendskeywordisusedto
extendaninterface,andthechildinterfaceinheritsthemethodsoftheparentinterface.
ThefollowingSportsinterfaceisextendedbyHockeyandFootballinterfaces.

http://www.tutorialspoint.com/java/java_interfaces.htm

2/4

7/16/2016

JavaInterfaces

//Filename:Sports.java
publicinterfaceSports
{
publicvoidsetHomeTeam(Stringname);
publicvoidsetVisitingTeam(Stringname);
}
//Filename:Football.java
publicinterfaceFootballextendsSports
{
publicvoidhomeTeamScored(intpoints);
publicvoidvisitingTeamScored(intpoints);
publicvoidendOfQuarter(intquarter);
}
//Filename:Hockey.java
publicinterfaceHockeyextendsSports
{
publicvoidhomeGoalScored();
publicvoidvisitingGoalScored();
publicvoidendOfPeriod(intperiod);
publicvoidovertimePeriod(intot);
}

TheHockeyinterfacehasfourmethods,butitinheritstwofromSportsthus,aclassthatimplementsHockeyneedstoimplementallsix
methods.Similarly,aclassthatimplementsFootballneedstodefinethethreemethodsfromFootballandthetwomethodsfromSports.

ExtendingMultipleInterfaces:
AJavaclasscanonlyextendoneparentclass.Multipleinheritanceisnotallowed.Interfacesarenotclasses,however,andaninterface
canextendmorethanoneparentinterface.
Theextendskeywordisusedonce,andtheparentinterfacesaredeclaredinacommaseparatedlist.
Forexample,iftheHockeyinterfaceextendedbothSportsandEvent,itwouldbedeclaredas:
publicinterfaceHockeyextendsSports,Event

TaggingInterfaces:
The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the
MouseListenerinterfaceinthejava.awt.eventpackageextendedjava.util.EventListener,whichisdefinedas:
packagejava.util;
publicinterfaceEventListener
{}

Aninterfacewithnomethodsinitisreferredtoasatagginginterface.Therearetwobasicdesignpurposesoftagginginterfaces:
Createsacommonparent:AswiththeEventListenerinterface,whichisextendedbydozensofotherinterfacesintheJavaAPI,you
can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends
EventListener,theJVMknowsthatthisparticularinterfaceisgoingtobeusedinaneventdelegationscenario.
Addsadatatypetoaclass:Thissituationiswherethetermtaggingcomesfrom.Aclassthatimplementsatagginginterfacedoesnot
needtodefineanymethods(sincetheinterfacedoesnothaveany),buttheclassbecomesaninterfacetypethroughpolymorphism.

PreviousPage

NextPage
Advertisements

http://www.tutorialspoint.com/java/java_interfaces.htm

3/4

7/16/2016

JavaInterfaces

Write for us

FAQ's

Helping

Contact

Copyright 2016. All Rights Reserved.


Enter email for newsletter

http://www.tutorialspoint.com/java/java_interfaces.htm

go

4/4

Você também pode gostar