CINXE.COM

What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>What Is an Interface? (The Java&trade; Tutorials &gt; Learning the Java Language &gt; Object-Oriented Programming Concepts) </title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="description" content="This beginner Java tutorial describes fundamentals of programming in the Java programming language" /> <meta name="keywords" content="java programming, learn java, java sample code, java objects, java classes, java inheritance, interfaces, variables, arrays, data types, operators, control flow, number, string, package, expression, statement, block, enum, annotation, character, generics" /> <style type="text/css"> body { margin-left:10px; margin-right:10px; line-height: 1.5; FONT-FAMILY: Arial, Helvetica, sans-serif; font-size: 0.8em; } a:link{text-decoration:none; color:#09569d;} a:visited{text-decoration:none; color: #3a87cf;} a:hover{text-decoration:underline; } code{ font-family:Monaco,Courier,"Courier New"; } .header-container { background-color: #fff; border-bottom: 1px solid #C1CFDA; -webkit-box-shadow: 0 2px 2px rgba(117, 163, 231, 0.1); box-shadow: 0 2px 2px rgba(117, 163, 231, 0.1); } .bookwrapper { width: auto; margin: auto; } .clearfix { } .clearfloat { clear: both; overflow: auto; height: 0px; font-size: 1px; line-height: 0px; } #brandProdName { width: auto; height: auto; } #logocover { display: block; background: transparent url(../../images/oracle-java-logo.png) 0px 0px no-repeat; height: 50px; width: 229px; float: left; } #productName { font-size: 16px; position: relative; top: 19px; padding-left: 3px; color: #457798; white-space: nowrap; width: 340px; } .FigureCaption { font-family: sans-serif; text-align: center; } #TopBar_bl { width: 100%; height: 60px; } #TopBar_br { width: 100%; height: 60px; } #TopBar_tl { margin-left: -110px; margin-right: -100px; align: left; height: 60px; } #TopBar_tr { width: 100%; height: 60px; } #TopBar { min-width:700px; padding:25px 100px 10px; margin-bottom:25px; clear:both; border-bottom:1px solid #d2dde5; border-radius: 3px; background:#efefef; /* Old browsers */ /* IE9 SVG, needs conditional override of 'filter' to 'none' */ background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNlMmVmZjkiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+); background: -moz-linear-gradient(top, #ffffff 0%, #e2eff9 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e2eff9)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #ffffff 0%,#e2eff9 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #ffffff 0%,#e2eff9 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #ffffff 0%,#e2eff9 100%); /* IE10+ */ background: linear-gradient(to bottom, #ffffff 0%,#e2eff9 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e2eff9',GradientType=0 ); /* IE6-8 */ } #TopBar_left { line-height: 14px; position: absolute; padding-top: 30px; padding-right: 30px; padding-left: 30px; text-align: left; font: 13px/20px Arial, Helvetica, sans-serif; font-weight: bold; font-size: 20px; color: #333; } #TopBar_right { line-height: 12px; float: right; padding-top: 10px; padding-right: 30px; text-align: left; } @media print { #BreadCrumbs, #Download { display: none; } } @media print { #TopBar_right { display: none; } } #TopBar_right a { font-size: 10px; margin: 3px; padding: 0; } #BreadCrumbs { padding: 15px 5px 0.5em 0; font-family: sans-serif; float: right; } #BreadCrumbs a { color:#09569d; } #BreadCrumbs a:visited, #BreadCrumbs a:link { text-decoration: none; } #BreadCrumbs a:hover, #BreadCrumbs a:active { text-decoration: underline; } #PageTitle { margin: 0 5px 0.5em 0; color: #F90000; } #PageContent{ margin: 0 5px 0 20px; } .LeftBar_shown { width: 13em; float: left; } @media print { .LeftBar_shown { display: none; } } .LeftBar_hidden { display: none; } #Footer { padding-top: 10px; padding-left: 10px; margin-right: 10px; } .footertext { font-size: 10px; font-family: sans-serif; margin-top: 1px; } .NavBit { padding: 15px 5px 0.5em 0; font-family: sans-serif; } @media print { .NavBit { display: none; } } #TagNotes { text-align: right; } @media print { #TagNotes a:visited, #TagNotes a:link { color: #35556B; text-decoration: none; } } #Contents a, .NavBit a, #TagNotes a { color:#09569d; } #TagNotes a:visited, #TagNotes a:link, #Contents a:visited, #Contents a:link, .NavBit a:visited, .NavBit a:link { text-decoration: none; } #TagNotes a:hover, #TagNotes a:active, #Contents a:hover, #Contents a:active, .NavBit a:hover, .NavBit a:active { text-decoration: underline; } #Contents { float: left; font-family: sans-serif; } @media print { #Contents { display: none; } } @media screen { div.PrintHeaders { display: none; } } .linkLESSON, .nolinkLESSON { margin-left: 0.5em; text-indent: -0.5em; } .linkAHEAD, .nolinkAHEAD, .linkQUESTIONS, .nolinkQUESTIONS { margin-left: 1.5em; text-indent: -0.5em } .linkBHEAD, .nolinkBHEAD { margin-left: 2.5em; text-indent: -0.5em } .linkCHEAD, .nolinkCHEAD { margin-left: 3.5em; text-indent: -0.5em } .nolinkLESSON, .nolinkAHEAD, .nolinkBHEAD, .nolinkCHEAD, .nolinkQUESTIONS { font-weight: bold; color: #333; } .MainFlow_indented { margin-right: 10px; margin-left: 15em; margin-bottom: 2em; } .MainFlow_wide { margin-right: 10px; margin-left: 10px; margin-bottom: 2em; } @media print { .MainFlow_indented, .MainFlow_wide { padding-top: 0; margin-top: 10px; margin-right: 10px; margin-left: 0; } } h1, h2, h3, h4, h5 { color: #333; } h1 { font-weight: bold; font-size: 20px; } h2 { font-weight: bold; font-size: 17px; } h3 { font-weight: bold; font-size: 14px; } h4 { font-size: 15px; } h5 { font-size: 12px; } #ToggleLeft { display: none; } .note { margin: 0 30px 0px 30px; } .codeblock { margin: 0 30px 0px 30px; font-size:12px; font-family:Monaco,Courier,"Courier New"; } .tocli { list-style-type:none; } .betadraft { color: red; } </style> <script type="text/javascript"> /* <![CDATA[ */ function leftBar() { var nameq = 'tutorial_showLeftBar=' var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookieString = cookies[i]; while (cookieString.charAt(0) == ' ') { cookieString = cookieString.substring(1, cookieString.length); } if (cookieString.indexOf(nameq) == 0) { cookieValue = cookieString.substring(nameq.length, cookieString.length); return cookieValue == 'yes'; } } return true; } function showLeft(b) { var contents = document.getElementById("LeftBar"); var main = document.getElementById("MainFlow"); var toggle = document.getElementById("ToggleLeft"); if (b) { contents.className = "LeftBar_shown"; main.className = "MainFlow_indented"; toggle.innerHTML = "Hide TOC"; document.cookie = 'tutorial_showLeftBar=yes; path=/'; } else { contents.className = "LeftBar_hidden"; main.className = "MainFlow_wide"; toggle.innerHTML = "Show the TOC"; document.cookie = 'tutorial_showLeftBar=no; path=/'; } } function toggleLeft() { showLeft(document.getElementById("LeftBar").className == "LeftBar_hidden"); document.getElementById("ToggleLeft").blur(); } function load() { showLeft(leftBar()); document.getElementById("ToggleLeft").style.display="inline"; } function showCode(displayCodePage, codePath) { var codePathEls = codePath.split("/"); var currDocPathEls = location.href.split("/"); //alert ("codePathEls = " + codePathEls + "\n" + "currDocPathEls = " + currDocPathEls); currDocPathEls.pop(); // remove file name at the end while (codePathEls.length > 0) { if (codePathEls[0] == "..") { codePathEls.shift(); currDocPathEls.pop(); } else { break; } } var fullCodePath = currDocPathEls.join("/") + "/" + codePathEls.join("/"); //alert ("fullCodePath = " + fullCodePath ); if (codePath.indexOf(".java") != -1 || codePath.indexOf(".jnlp") != -1) { window.location.href = displayCodePage + "?code=" + encodeURI(fullCodePath); } else { window.location.href = fullCodePath; } } /* ]]> */ </script> <script>window.ohcglobal || document.write('<script src="/en/dcommon/js/global.js">\x3C/script>')</script></head> <body onload="load()"> <noscript> A browser with JavaScript enabled is required for this page to operate properly. </noscript> <!-- header --> <div class="header-container"> <div class="bookwrapper clearfix"> <div id="brandProdName"> <div id="logocover"></div> <div id="productName" >Documentation</div> </div> <br class="clearfloat" /> </div> </div> <div id="TopBar"> <div id="TopBar_tr"> <div id="TopBar_tl"> <div id="TopBar_br"> <div id="TopBar_bl"> <div id="TopBar_left">The Java&trade; Tutorials</div> <div id="TopBar_right"> <!-- <a href="URL" target="_blank">External Link</a><br/> --> <script type="text/javascript">function search() { var sform = document.getElementById("searchForm"); var srchelem = document.getElementById("searchField"); var srchelemreal = document.getElementById("keywordreal"); var srchval = srchelem.value; if (srchval.length == 0) { return false; } srchelemreal.value = srchval; sform.action = "http://docs.oracle.com/apps/search/search.jsp"; sform.method = "get"; sform.target = "_blank"; sform.submit(); }</script><form id="searchForm" onsubmit="return search()"><input type="hidden" name="category" value="java"/><input type="hidden" name="product" value="e25407-01"/><input type="hidden" name="q" value="" id="keywordreal"/><label for="searchField"><input type="text" id="searchField" size="30" onclick="this.value='';" /></label><input type="submit" value="Search" /></form> <a href="javascript:toggleLeft()" id="ToggleLeft">Hide TOC</a> </div> </div> </div> </div> </div> </div> <div id="LeftBar" class="LeftBar_shown"> <div id="Contents"> <div class="linkLESSON"><a href="index.html">Object-Oriented Programming Concepts</a></div> <div class="linkAHEAD"><a href="object.html">What Is an Object?</a></div> <div class="linkAHEAD"><a href="class.html">What Is a Class?</a></div> <div class="linkAHEAD"><a href="inheritance.html">What Is Inheritance?</a></div> <div class="nolinkAHEAD">What Is an Interface?</div> <div class="linkAHEAD"><a href="package.html">What Is a Package?</a></div> <div class="linkQUESTIONS"><a href="QandE/questions.html">Questions and Exercises</a></div> </div> </div> <div id="MainFlow" class="MainFlow_indented"> <div class="PrintHeaders"> <b>Trail:</b> Learning the Java Language <br /><b>Lesson:</b> Object-Oriented Programming Concepts </div> <div id="BreadCrumbs"> <a href="../../index.html" target="_top">Home Page</a> &gt; <a href="../index.html" target="_top">Learning the Java Language</a> &gt; <a href="index.html" target="_top">Object-Oriented Programming Concepts</a> </div> <div class="NavBit"> <a target="_top" href="inheritance.html">&laquo;&nbsp;Previous</a>&nbsp;&bull;&nbsp;<a target="_top" href="../TOC.html">Trail</a>&nbsp;&bull;&nbsp;<a target="_top" href="package.html">Next&nbsp;&raquo;</a> </div> <div class="Banner"><p style="background-color: rgb(247, 248, 249); border-width: 1px; padding: 10px; font-style: italic; border-style: solid; border-color: rgb(64, 74, 91);">The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.<br/>See <a href="https://dev.java/learn/">Dev.java</a> for updated tutorials taking advantage of the latest releases.<br/>See <a href="https://docs.oracle.com/pls/topic/lookup?ctx=en/java/javase&id=java_language_changes">Java Language Changes</a> for a summary of updated language features in Java SE 9 and subsequent releases.<br/>See <a href="https://www.oracle.com/technetwork/java/javase/jdk-relnotes-index-2162236.html">JDK Release Notes</a> for information about new features, enhancements, and removed or deprecated options for all JDK releases.</p></div> <div id="PageTitle"><h1>What Is an Interface?</h1></div> <div id="PageContent"> <!-- What is Inheritance? --> <p>As you&#39;ve already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object&#39;s <i>interface</i> with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the &quot;power&quot; button to turn the television on and off.</p> <p>In its most common form, an interface is a group of related methods with empty bodies. A bicycle&#39;s behavior, if specified as an interface, might appear as follows:</p> <div class="codeblock"><pre> interface Bicycle { // wheel revolutions per minute void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } </pre></div> <p>To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as <code>ACMEBicycle</code>), and you&#39;d use the <code>implements</code> keyword in the class declaration:</p> <div class="codeblock"><pre> class ACMEBicycle <strong>implements</strong> Bicycle { int cadence = 0; int speed = 0; int gear = 1; // The compiler will now require that methods // changeCadence, changeGear, speedUp, and applyBrakes // all be implemented. Compilation will fail if those // methods are missing from this class. void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); } } </pre></div> <p>Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.</p> <div class="note"><hr /><strong>Note:</strong>&nbsp;To actually compile the <code>ACMEBicycle</code> class, you&#39;ll need to add the <code>public</code> keyword to the beginning of the implemented interface methods. You&#39;ll learn the reasons for this later in the lessons on <a class="TutorialLink" target="_top" href="../javaOO/index.html">Classes and Objects</a> and <a class="TutorialLink" target="_top" href="../IandI/index.html">Interfaces and Inheritance</a>. <hr /></div> </div> <div class="NavBit"> <a target="_top" href="inheritance.html">&laquo; Previous</a> &bull; <a target="_top" href="../TOC.html">Trail</a> &bull; <a target="_top" href="package.html">Next &raquo;</a> </div> </div> <hr class="clearfloat"/> <div id="Footer"> <p class="footertext"> <a href="https://www.oracle.com/corporate/">About Oracle</a> | <a href="https://www.oracle.com/corporate/contact/">Contact Us</a> | <a href="https://www.oracle.com/legal/">Legal Notices</a> | <a href="https://www.oracle.com/legal/terms.html">Terms of Use</a> | <a href="https://www.oracle.com/legal/privacy/">Your Privacy Rights</a></p> <p class="footertext"><a href="http://www.oracle.com/pls/topic/lookup?ctx=cpyr&id=en-US"> Copyright &copy; 1995, 2024 Oracle and/or its affiliates. All rights reserved.</a></p> </div> <div class="PrintHeaders"> <b>Previous page:</b> What Is Inheritance? <br /><b>Next page:</b> What Is a Package? </div> <!-- Start SiteCatalyst code --> <script type="application/javascript" src="https://www.oracleimg.com/us/assets/metrics/ora_docs.js"></script> <!-- End SiteCatalyst code --> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10