Title: Java Interface Example - Java Code Geeks
Open Graph Title: Java Interface Example - Java Code Geeks
Description: Check out our detailed Java Interface Example!Java interface is an abstract type that defines methods that classes must implement
Open Graph Description: Check out our detailed Java Interface Example!Java interface is an abstract type that defines methods that classes must implement
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-interface-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-interface-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-interface-example/"},"author":{"name":"Mary Zheng","@id":"https://examples.javacodegeeks.com/#/schema/person/8a2034fbabcb20a9396e9819261855ae"},"headline":"Java Interface Example","datePublished":"2019-06-28T08:00:56+00:00","dateModified":"2022-07-07T13:09:23+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-interface-example/"},"wordCount":734,"commentCount":0,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-interface-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-interface-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-interface-example/","url":"https://examples.javacodegeeks.com/java-interface-example/","name":"Java Interface Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-interface-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-interface-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2019-06-28T08:00:56+00:00","dateModified":"2022-07-07T13:09:23+00:00","description":"Check out our detailed Java Interface Example!Java interface is an abstract type that defines methods that classes must implement","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-interface-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-interface-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-interface-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-interface-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"Java Interface Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/8a2034fbabcb20a9396e9819261855ae","name":"Mary Zheng","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2017/11/Mary-Zheng_avatar_1510732235-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2017/11/Mary-Zheng_avatar_1510732235-96x96.jpg","caption":"Mary Zheng"},"description":"Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.","url":"https://examples.javacodegeeks.com/author/mary-zheng/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2019-06-28T11:00:56+03:00","datePublished":"2019-06-28T11:00:56+03:00","dateModified":"2022-07-07T16:09:23+03:00","headline":"Java Interface Example","name":"Java Interface Example","keywords":[],"url":"https:\/\/examples.javacodegeeks.com\/java-interface-example\/","description":"In this post, we feature a comprehensive Java Interface Example. You can also check this tutorial in the following video: Java Interface Example - video 1. Introduction Java interface is an abstract t","copyrightYear":"2019","articleSection":"Core Java","articleBody":"\n In this post, we feature a comprehensive Java Interface Example. \n\n\n\nYou can also check this tutorial in the following video:\n\n\n\nJava Interface Example - video\n\n\n\n1. Introduction\n\n\n\nJava interface is an abstract type that defines methods that classes must implement. It can contain constants, abstract method signatures, default methods along with an implementation body, static methods along with an implementation body, and nested types. Java Interface defines the \"contracts\" and represents the IS-A relationship. Interface design pattern is one of the best known patterns in software engineering. \n\n\n\nJava defines lots of interfaces. Interface List is a well-known example. Java implements it with several implementation classes: AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector.\n\n\n\nIn this example, I will create a maven project to demonstrate the following interface features:\n\n\n\nDefining an interface which contains default, static, private, and abstract methodsDefining an interface which extends from one or more interfacesCreating an implementation class from a single interfaceCreating an implementation class from multiple interfacesUtilizing the interface design pattern in an application\n\n\n\n2. Technologies Used\n\n\n\nThe example code in this example was built and run with:\n\n\n\nJava 11Maven 3.3EclipseJunit 4.12Logback\n\n\n\n3. Maven Project\n\n\n\n3.1 Dependencies\n\n\n\nI will include both Junit and Logback in the pom.xml.\n\n\n\npom.xml\n\n\n\n\n<project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\"\n xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n xsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\">\n <modelVersion>4.0.0<\/modelVersion>\n <groupId>jcg-zheng-interface-demo<\/groupId>\n <artifactId>jcg-zheng-interface-demo<\/artifactId>\n <version>0.0.1-SNAPSHOT<\/version>\n <build>\n <sourceDirectory>src<\/sourceDirectory>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin<\/artifactId>\n <version>3.8.0<\/version>\n <configuration>\n <release>11<\/release>\n <\/configuration>\n <\/plugin>\n <\/plugins>\n <\/build>\n <dependencies>\n <dependency>\n <groupId>junit<\/groupId>\n <artifactId>junit<\/artifactId>\n <version>4.12<\/version>\n <\/dependency>\n <dependency>\n <groupId>ch.qos.logback<\/groupId>\n <artifactId>logback-access<\/artifactId>\n <version>1.2.3<\/version>\n <\/dependency>\n\n <dependency>\n <groupId>ch.qos.logback<\/groupId>\n <artifactId>logback-classic<\/artifactId>\n <version>1.2.3<\/version>\n <\/dependency>\n <dependency>\n <groupId>ch.qos.logback<\/groupId>\n <artifactId>logback-core<\/artifactId>\n <version>1.2.3<\/version>\n <\/dependency>\n <\/dependencies>\n<\/project>\n\n\n\n4. Interfaces\n\n\n\nIn this step, I will created five interfaces based on the following diagram.\n\n\n\nFigure 1 Interfaces\n\n\n\n4.1 MusicalInstrument\n\n\n\nIn this step, I will create a MusicalInstrument interface which contains:\n\n\n\nstatic String PLAY_MSG - a constant string value of \" plays \"private static boolean isBroke() - a private method which returns a true or false valuepublic static String repair() - a public static method which repairs a musical instrument. default String demo() - a default method which returns a messageString instrumentName() - a public abstract method which every implementation class must implementvoid play(String song) - a public abstract method which every implementation class must implementprivate String playMsg() - a private method which returns a String value\n\n\n\nMusicalInstrument.java\n\n\n\n\npackage jcg.zheng.demo.api;\n\nimport java.util.Random;\n\n\/**\n * \n * Interface defines \"contracts\"\n * \n * JDK 8\n * \n * 1) add Default interface method to preserve backward compatibility when\n * modifying an interface by adding new methods when the interface has more than\n * one implementations. Adding new methods will force all the implementation to\n * implement these new methods. With Default interface method solve this issue.\n * 2) add static method\n * \n * JDK 9 add private method\n *\n *\/\npublic interface MusicalInstrument {\n\n\tstatic String PLAY_MSG = \" plays : \";\n\n\tprivate static boolean isBroke() {\n\t\tboolean isBroke = false;\n\t\tRandom ran = new Random();\n\n\t\tint nxt = ran.nextInt();\n\t\tif (nxt % 8 == 0) {\n\t\t\tisBroke = true;\n\t\t}\n\t\treturn isBroke;\n\t}\n\n\t\/**\n\t * repair the instrument\n\t * \n\t * @param isBroke\n\t * @return a message show the repair result;\n\t *\/\n\tpublic static String repair() {\n\t\tif (isBroke()) {\n\t\t\treturn \"Fixed\";\n\t\t}\n\n\t\treturn \"In good condition\";\n\t}\n\n\t\/**\n\t * Play demo song\n\t * \n\t * @return\n\t *\/\n\tdefault String demo() {\n\t\treturn instrumentName() + playMsg();\n\t}\n\n\t\/**\n\t * Return the musical instrument name\n\t * \n\t * @return the musical instrument name\n\t *\/\n\tString instrumentName();\n\n\t\/**\n\t * Play the given song\n\t * \n\t * @param song the song to play\n\t *\/\n\tvoid play(String song);\n\n\tprivate String playMsg() {\n\t\treturn \" plays a demo song\";\n\t}\n}\n\n\n\n\n4.2 BrassInstrument\n\n\n\nIn this step, I will create a BrassInstrument interface which extends from MusicalInstrument with an additional buzz(String song) method.\n\n\n\nBrassInstrument.java\n\n\n\n\npackage jcg.zheng.demo.api;\n\npublic interface BrassInstrument extends MusicalInstrument {\n\t\/**\n\t * Make a buzz sound for the given song\n\t * \n\t * @param song the given song\n\t *\/\n\tvoid buzz(String song);\n}\n\n\n\n\n4.3 StringInstrument\n\n\n\nIn this step, I will create a StringInstrument interface which extends from MusicalInstrument along with two additional methods: bow(String song) and pluck(String song). \n\n\n\nStringInstrument.java\n\n\n\n\npackage jcg.zheng.demo.api;\n\npublic interface StringInstrument extends MusicalInstrument {\n\n\t\/**\n\t * Play the song with a bow\n\t * \n\t * @param song\n\t *\/\n\tvoid bow(String song);\n\n\t\/**\n\t * Play the song by plucking\n\t * \n\t * @param song\n\t *\/\n\tvoid pluck(String song);\n\n}\n\n\n\n\n4.4 ChildrenToy\n\n\n\nIn this step, I will create a ChildrenToy interface which has one default method - demo .\n\n\n\nChildrenToy.java\n\n\n\n\npackage jcg.zheng.demo.api;\n\npublic interface ChildrenToy {\n\t\/**\n\t * Play the demo song\n\t * \n\t * @return the demo song\n\t *\/\n\tdefault String demo() {\n\t\treturn \"Play the demo song\";\n\t}\n\n}\n\n\n\n\n4.5 PercussionInstrument\n\n\n\nIn this step, I will create a PercussionInstrument interface which extends from both MusicalInstrument and ChildrenToy interfaces. I will override the demo method because both parent interfaces have the demo method. \n\n\n\nPercussionInstrument.java\n\n\n\n\npackage jcg.zheng.demo.api;\n\npublic interface PercussionInstrument extends MusicalInstrument, ChildrenToy {\n\n\t\/**\n\t * use the MusicalInstrument demo sine both interface has demo\n\t *\/\n\t@Override\n\tdefault String demo() {\n\t\treturn MusicalInstrument.super.demo();\n\t}\n\n\t\/**\n\t * Play the song by hitting\n\t * \n\t * @param song\n\t *\/\n\tvoid hit(String song);\n\n\t\/**\n\t * Play the song by shaking\n\t * \n\t * @param song\n\t *\/\n\tvoid shake(String song);\n\n}\n\n\n\n\n5. Implementation Classes\n\n\n\nIn this step, I will create nine implementation classes base on the following diagram. \n\n\n\nFigure 2 Interfaces and Implementation Classes\n\n\n\n5.1 Bell\n\n\n\nIn this step, I will create a Bell class which implements the PercussionInstrument interface.\n\n\n\nBell.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.PercussionInstrument;\n\npublic class Bell implements PercussionInstrument {\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\t@Override\n\tpublic void hit(String song) {\n\t\tlogger.info(instrumentName() + PLAY_MSG + song);\n\t}\n\n\t@Override\n\tpublic String instrumentName() {\n\t\treturn \"Bell\";\n\t}\n\n\t@Override\n\tpublic void play(String song) {\n\t\tshake(song);\n\t}\n\n\t@Override\n\tpublic void shake(String song) {\n\t\tlogger.info(instrumentName() + PLAY_MSG + song);\n\t}\n\n}\n\n\n\n\n5.2 Drum\n\n\n\nIn this step, I will create a Drum class which implements the PercussionInstrument interface.\n\n\n\nDrum.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.PercussionInstrument;\n\npublic class Drum implements PercussionInstrument {\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public void hit(String song) {\n logger.info(instrumentName() + PLAY_MSG + song);\n }\n\n @Override\n public String instrumentName() {\n return \"Drum\";\n }\n\n @Override\n public void play(String song) {\n hit(song);\n }\n\n @Override\n public void shake(String song) {\n throw new UnsupportedOperationException();\n }\n\n}\n\n\n\n5.3 KidDrumToy\n\n\n\nIn this step, I will create a KidDrumToy class which implements the PercussionInstrument interface. \n\n\n\nKidDrumToy.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.PercussionInstrument;\n\npublic class KidDrumToy implements PercussionInstrument {\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public String demo() {\n return \"KidDrumToy play the demo song by hitting and shaking\";\n }\n\n @Override\n public void hit(String song) {\n logger.info(instrumentName() + PLAY_MSG + song + \" when is hit.\");\n }\n\n @Override\n public String instrumentName() {\n return \"KidMusicToy\";\n }\n\n @Override\n public void play(String song) {\n hit(song);\n shake(song);\n }\n\n @Override\n public void shake(String song) {\n logger.info(instrumentName() + PLAY_MSG + song + \" when is shaked.\");\n }\n\n}\n\n\n\n5.4 KidMusicalToy\n\n\n\n In this step, I will create a KidMusicalToy class which implements both PercussionInstrument and StringInstrument interfaces.\n\n\n\nKidMusicalToy.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.BrassInstrument;\nimport jcg.zheng.demo.api.StringInstrument;\n\npublic class KidMusicalToy implements BrassInstrument, StringInstrument {\n\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public void bow(String song) {\n logger.info(\"play a string with a bow \" + song);\n }\n\n @Override\n public void buzz(String song) {\n logger.info(\"make a buzz sound \" + song);\n }\n\n @Override\n public String demo() {\n return \"KidMusicToy play the demo song with String and buzz\";\n }\n\n @Override\n public String instrumentName() {\n return \"KidMusicToy\";\n }\n\n @Override\n public void play(String song) {\n bow(song);\n pluck(song);\n buzz(song);\n }\n\n @Override\n public void pluck(String song) {\n logger.info(\"play a string with a pluck sound \" + song);\n\n }\n\n}\n\n\n\n5.5 Trumpet\n\n\n\nIn this step, I will create a Trumpet class which implements the BrassInstrument interface.\n\n\n\nTrumpet.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.BrassInstrument;\n\npublic class Trumpet implements BrassInstrument {\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public void buzz(String song) {\n logger.info(instrumentName() + PLAY_MSG + song);\n }\n\n @Override\n public String instrumentName() {\n return \"Trumpet\";\n }\n\n @Override\n public void play(String song) {\n buzz(song);\n }\n\n}\n\n\n\n5.6 Tuba\n\n\n\nIn this step, I will create a Tuba class which implements the BrassInstrument interface.\n\n\n\nTuba.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.BrassInstrument;\n\npublic class Tuba implements BrassInstrument {\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public void buzz(String song) {\n logger.info(instrumentName() + PLAY_MSG + song);\n }\n\n @Override\n public String demo() {\n return \"Tuba overrides the default demo method\";\n }\n\n @Override\n public String instrumentName() {\n return \"Tuba\";\n }\n\n @Override\n public void play(String song) {\n buzz(song);\n }\n\n}\n\n\n\n5.7 Viola\n\n\n\nIn this step, I will create a Viola class which implements the StringInstrument interface.\n\n\n\nViola.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.StringInstrument;\n\npublic class Viola implements StringInstrument {\n\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public void bow(String song) {\n logger.info(instrumentName() + PLAY_MSG + song);\n }\n\n @Override\n public String instrumentName() {\n return \"Viola\";\n }\n\n @Override\n public void play(String song) {\n bow(song);\n }\n\n @Override\n public void pluck(String song) {\n throw new UnsupportedOperationException();\n }\n\n}\n\n\n\n5.8 Violin\n\n\n\n In this step, I will create a Violin class which implements the StringInstrument interface.\n\n\n\nViolin.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.StringInstrument;\n\npublic class Violin implements StringInstrument {\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public void bow(String song) {\n logger.info(instrumentName() + PLAY_MSG + song);\n }\n\n @Override\n public String instrumentName() {\n return \"Violin\";\n }\n\n @Override\n public void play(String song) {\n bow(song);\n }\n\n @Override\n public void pluck(String song) {\n throw new UnsupportedOperationException();\n }\n\n}\n\n\n\n5.9 Violin2\n\n\n\n In this step, I will create a Violin2 class which implements the StringInstrument interface.\n\n\n\nViolin2.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport jcg.zheng.demo.api.StringInstrument;\n\npublic class Violin2 implements StringInstrument {\n\n private final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n @Override\n public void bow(String song) {\n logger.info(instrumentName() + PLAY_MSG + song);\n }\n\n @Override\n public String instrumentName() {\n return \"Violin2\";\n }\n\n @Override\n public void play(String song) {\n bow(song);\n }\n\n @Override\n public void pluck(String song) {\n throw new UnsupportedOperationException();\n }\n}\n\n\n\n6. Junit Tests\n\n\n\n6.1 AbstractionTest\n\n\n\nIn this step, I will create an AbstractionTest class which has a list of MusicalInstruments and invokes its default demo method and abstract play method. I will use the logger to print out the messages.\n\n\n\nAbstractionTest.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport jcg.zheng.demo.api.MusicalInstrument;\n\npublic class AbstractionTest {\n\n\tList<MusicalInstrument> musicInstruments = new ArrayList<>();\n\n\t@Test\n\tpublic void polymorphism_with_abstract_method() {\n\t\tmusicInstruments.forEach(mi -> mi.play(\"Hello\"));\n\t}\n\n\t@Test\n\tpublic void polymorphism_with_default_method() {\n\t\tmusicInstruments.forEach(mi -> System.out.println(mi.demo()));\n\t}\n\n\t@Before\n\tpublic void setupBand() {\n\t\tmusicInstruments.add(new Violin());\n\t\tmusicInstruments.add(new Viola());\n\t\tmusicInstruments.add(new Bell());\n\t\tmusicInstruments.add(new Drum());\n\t\tmusicInstruments.add(new Trumpet());\n\t\tmusicInstruments.add(new Tuba());\n\t\tmusicInstruments.add(new KidMusicalToy());\n\t\tmusicInstruments.add(new KidDrumToy());\n\t\tmusicInstruments.add(new Violin2());\n\n\t}\n\n}\n\n\n\n\nExecute mvn test -Dtest=AbstractionTest command and capture the output here.\n\n\n\nOutput\n\n\n\n\nC:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo>mvn test -Dtest=AbstractionTest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ---------< jcg-zheng-interface-demo:jcg-zheng-interface-demo >----------\n[INFO] Building jcg-zheng-interface-demo 0.0.1-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ jcg-zheng-interface-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ jcg-zheng-interface-demo ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 17 source files to C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ jcg-zheng-interface-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ jcg-zheng-interface-demo ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ jcg-zheng-interface-demo ---\n[INFO] Surefire report directory: C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning jcg.zheng.demo.api.impl.AbstractionTest\nViolin plays a demo song\nViola plays a demo song\nBell plays a demo song\nDrum plays a demo song\nTrumpet plays a demo song\nTuba overrides the default demo method\nKidMusicToy play the demo song with String and buzz\nKidDrumToy play the demo song by hitting and shaking\nViolin2 plays a demo song\n21:34:55.464 [main] INFO jcg.zheng.demo.api.impl.Violin - Violin plays : Hello\n21:34:55.472 [main] INFO jcg.zheng.demo.api.impl.Viola - Viola plays : Hello\n21:34:55.473 [main] INFO jcg.zheng.demo.api.impl.Bell - Bell plays : Hello\n21:34:55.476 [main] INFO jcg.zheng.demo.api.impl.Drum - Drum plays : Hello\n21:34:55.478 [main] INFO jcg.zheng.demo.api.impl.Trumpet - Trumpet plays : Hello\n21:34:55.482 [main] INFO jcg.zheng.demo.api.impl.Tuba - Tuba plays : Hello\n21:34:55.497 [main] INFO jcg.zheng.demo.api.impl.KidMusicalToy - play a string with a bow Hello\n21:34:55.498 [main] INFO jcg.zheng.demo.api.impl.KidMusicalToy - play a string with a pluck sound Hello\n21:34:55.499 [main] INFO jcg.zheng.demo.api.impl.KidMusicalToy - make a buzz sound Hello\n21:34:55.516 [main] INFO jcg.zheng.demo.api.impl.KidDrumToy - KidMusicToy plays : Hello when is hit.\n21:34:55.517 [main] INFO jcg.zheng.demo.api.impl.KidDrumToy - KidMusicToy plays : Hello when is shaked.\n21:34:55.519 [main] INFO jcg.zheng.demo.api.impl.Violin2 - Violin2 plays : Hello\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.577 sec\n\nResults :\n\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 9.610 s\n[INFO] Finished at: 2019-06-25T21:34:55-05:00\n[INFO] ------------------------------------------------------------------------\n\n\n\n\n6.2 RuntimeTest\n\n\n\nIn this step, I will create a RuntimeTest class which will create a different Violin class based on the condition.\n\n\n\nRuntimeTest.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.Test;\n\nimport jcg.zheng.demo.api.MusicalInstrument;\n\npublic class RuntimeTest {\n\n\t@Test\n\tpublic void runtime_injection() {\n\t\tMusicalInstrument violin = violinBuilder(false);\n\t\tassertEquals(Violin.class, violin.getClass());\n\n\t}\n\n\t@Test\n\tpublic void runtime_injection_2() {\n\t\tMusicalInstrument violin = violinBuilder(true);\n\t\tassertEquals(Violin2.class, violin.getClass());\n\n\t}\n\n\tprivate MusicalInstrument violinBuilder(boolean isVersion2) {\n\t\tMusicalInstrument violin;\n\t\tif (isVersion2) {\n\t\t\tviolin = new Violin2();\n\t\t} else {\n\t\t\tviolin = new Violin();\n\t\t}\n\t\treturn violin;\n\t}\n}\n\n\n\n\nExecute mvn test -Dtest=RuntimeTest command and capture the output here.\n\n\n\nOutput\n\n\n\n\nC:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo>mvn test -Dtest=RuntimeTest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ---------< jcg-zheng-interface-demo:jcg-zheng-interface-demo >----------\n[INFO] Building jcg-zheng-interface-demo 0.0.1-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ jcg-zheng-interface-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ jcg-zheng-interface-demo ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 17 source files to C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ jcg-zheng-interface-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ jcg-zheng-interface-demo ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ jcg-zheng-interface-demo ---\n[INFO] Surefire report directory: C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning jcg.zheng.demo.api.impl.RuntimeTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.338 sec\n\nResults :\n\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 9.608 s\n[INFO] Finished at: 2019-06-25T21:42:03-05:00\n[INFO] ------------------------------------------------------------------------\n\n\n\n6.3 StaticMethodTest\n\n\n\nIn this step, I will create a StaticMethodTest class to test the interface's static method.\n\n\n\nStaticMethodTest.java\n\n\n\n\npackage jcg.zheng.demo.api.impl;\n\nimport org.junit.Test;\n\nimport jcg.zheng.demo.api.MusicalInstrument;\n\npublic class StaticMethodTest {\n\t@Test\n\tpublic void test_static_method() {\n\t\tSystem.out.println(MusicalInstrument.repair());\n\t}\n}\n\n\n\n\nExecute mvn test -Dtest=StaticMethodTest command and capture the output here.\n\n\n\nOutput\n\n\n\n\nC:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo>mvn test -Dtest=StaticMethodTest\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ---------< jcg-zheng-interface-demo:jcg-zheng-interface-demo >----------\n[INFO] Building jcg-zheng-interface-demo 0.0.1-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ jcg-zheng-interface-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\src\\main\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ jcg-zheng-interface-demo ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!\n[INFO] Compiling 17 source files to C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\target\\classes\n[INFO]\n[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ jcg-zheng-interface-demo ---\n[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ jcg-zheng-interface-demo ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ jcg-zheng-interface-demo ---\n[INFO] Surefire report directory: C:\\MaryZheng\\Workspaces\\jdk12\\jcg-zheng-interface-demo\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning jcg.zheng.demo.api.impl.StaticMethodTest\nIn good condition\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.123 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 9.069 s\n[INFO] Finished at: 2019-06-25T21:43:10-05:00\n[INFO] ------------------------------------------------------------------------\n\n\n\n7. Java Interface Example - Summary\n\n\n\nIn this example, I demonstrated how to define interfaces and create its implementation classes. Java interface provides the following benefits:\n\n\n\nSupport polymorphism by sharing a standard set of methods in different ways. Support encapsulation by separating the method definition from the implementation.Supports multiple inheritances. Allow dependency injections during runtime \n\n\n\n8. Download the Source Code\n\n\n\nThis example consists of a Maven project which defines five interfaces and nine implementation classes and three junit test classes to show the interface abstraction and runtime object injection.\n\n\n\nDownload\nYou can download the full source code of this example here: Java Interface Example\n\n\n\nLast updated on Feb. 12th, 2020\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-interface-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Mary Zheng","url":"https:\/\/examples.javacodegeeks.com\/author\/mary-zheng\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2019-06-28T08:00:56+00:00 |
| article:modified_time | 2022-07-07T13:09:23+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Mary Zheng |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Mary Zheng |
| twitter:label2 | Est. reading time |
| twitter:data2 | 13 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1