What is the correct way to implement an interface example operation interface implements add class?
❮ Java Keywords Show
ExampleAn interface is an abstract "class" that is used to group related methods with "empty" bodies: To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class: // interface interface Animal { public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) } // Pig "implements" the Animal interface class Pig implements Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); } public void sleep() { // The body of sleep() is provided here System.out.println("Zzz"); } } class MyMainClass { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }Try it Yourself » Definition and UsageThe implements keyword is used to implement an interface. The interface keyword is used to declare a special type of class that only contains abstract methods. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class. Notes on Interfaces:
Why And When To Use Interfaces?To achieve security - hide certain details and only show the important details of an object (interface). Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below). Multiple InterfacesTo implement multiple interfaces, separate them with a comma: Exampleinterface FirstInterface { public void myMethod(); // interface method } interface SecondInterface { public void myOtherMethod(); // interface method } // DemoClass "implements" FirstInterface and SecondInterface class DemoClass implements FirstInterface, SecondInterface { public void myMethod() { System.out.println("Some text.."); } public void myOtherMethod() { System.out.println("Some other text..."); } } class MyMainClass { public static void main(String[] args) { DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); } }Try it Yourself » Related PagesRead more about interfaces in our Java Interface Tutorial. ❮ Java Keywords Interface in Java is a bit like the Class, but with a significant difference: an interface can only have method signatures, fields and default methods. Since Java 8, you can also create default methods. In the next block you can see an example of interface: The interface above contains two fields, two methods, and a default method. Alone, it is not of much use, but they are usually used along with Classes. How? Simple, you have to make sure some class implements it. public class Car implements Vehicle { public void start() { System.out.println("starting engine..."); } public void stop() { System.out.println("stopping engine..."); } }Now, there is a ground rule: The Class must implement all of the methods in the Interface. The methods must have the exact same signature (name, parameters and exceptions) as described in the interface. The class does not need to declare the fields though, only the methods. Instances of an InterfaceOnce you create a Java Class which implements any Interface, the object instance can be referenced as an instance of the Interface. This concept is similar to that of Inheritance instantiation. // following our previous example Vehicle tesla = new Car(); tesla.start(); // starting engine ...An Interface can not contain a constructor methods. Therefore, you can not create an instance of an Interface itself. You must create an instance of some class implementing an Interface to reference it. Think of interfaces as a blank contract form, or a template. What can you do with this feature? Polymorphism! You can use only interfaces to refer to object instances! class Truck implements Vehicle { public void start() { System.out.println("starting truck engine..."); } public void stop() { System.out.println("stopping truck engine..."); } } class Starter { // static method, can be called without instantiating the class public static void startEngine(Vehicle vehicle) { vehicle.start(); } } Vehicle tesla = new Car(); Vehicle tata = new Truck(); Starter.startEngine(tesla); // starting engine ... Starter.startEngine(tata); // starting truck engine ...But how about multiple interfaces?Yes, you can implement multiple Interfaces in a single class. While in Inheritance within Classes you were restricted to inherit only one class, here you can extend any number of interfaces. But do not forget to implement all of the methods of all the Interfaces, otherwise compilation will fail! public interface GPS { public void getCoordinates(); } public interface Radio { public void startRadio(); public void stopRadio(); } public class Smartphone implements GPS,Radio { public void getCoordinates() { // return some coordinates } public void startRadio() { // start Radio } public void stopRadio() { // stop Radio } }Some features of Interfaces
Interface Default MethodsBefore Java 8, we had no way to direct an Interface to have a particular method implementation. This lead to lot of confusion and code breaks if an Interface definition is suddenly changed. Suppose, you wrote an open source library, which contains an Interface. Say, your clients, i.e. practically all developers around the world, are using it heavily and are happy. Now you have had to upgrade the library by adding a new method definition to the Interface to support a new feature. But that would break all builds since all Classes implementing that Interface have to change now. What a catastrophe! Thankfully, Java 8 now provides us default methods for Interfaces. A default method can contain its own implementation directly within the Interface! So, if a Class does not implement a default method, the compiler will take the implementation mentioned within the Interface. Nice, isn’t it? So in your library, you may add any number of default methods in interfaces without the fear of breaking anything! public interface GPS { public void getCoordinates(); default public void getRoughCoordinates() { // implementation to return coordinates from rough sources // such as wifi & mobile System.out.println("Fetching rough coordinates..."); } } public interface Radio { public void startRadio(); public void stopRadio(); } public class Smartphone implements GPS,Radio { public void getCoordinates() { // return some coordinates } public void startRadio() { // start Radio } public void stopRadio() { // stop Radio } // no implementation of getRoughCoordinates() } Smartphone motoG = new Smartphone(); motog.getRoughCoordinates(); // Fetching rough coordinates...But, what happens if two interfaces have the same method signature? Awesome question. In that case, if you do not provide the implementation in the Class, poor compiler will get confused and simply fail! You have to provide a default method implementation within the Class also. There is also a nifty way using super to call which implementation you like: public interface Radio { // public void startRadio(); // public void stopRadio(); default public void next() { System.out.println("Next from Radio"); } } public interface MusicPlayer { // public void start(); // public void pause(); // public void stop(); default public void next() { System.out.println("Next from MusicPlayer"); } } public class Smartphone implements Radio, MusicPlayer { public void next() { // Suppose you want to call MusicPlayer next MusicPlayer.super.next(); } } Smartphone motoG = new Smartphone(); motoG.next(); // Next from MusicPlayerStatic Methods in InterfacesAlso new to Java 8 is the ability to add static methods to interfaces. Static methods in interfaces are almost identical to static methods in concrete classes. The only big difference is that static methods are not inherited in the classes that implement the interface. This means that the interface is referenced when calling the static method not the class that implements it. interface MusicPlayer { public static void commercial(String sponsor) { System.out.println("Now for a message brought to you by " + sponsor); } public void play(); } class Smartphone implements MusicPlayer { public void play() { System.out.println("Playing from smartphone"); } } class Main { public static void main(String[] args) { Smartphone motoG = new Smartphone(); MusicPlayer.commercial("Motorola"); // Called on interface not on implementing class // motoG.commercial("Motorola"); // This would cause a compilation error } }Inheriting an InterfaceIt is also possible in Java for an Interface to inherit another Interface, by using, you guessed it, extends keyword: public interface Player { public void start(); public void pause(); public void stop(); } public interface MusicPlayer extends Player { default public void next() { System.out.println("Next from MusicPlayer"); } }That means, the Class implementing MusicPlayer Interface has to implement all methods of MusicPlayer as well as Player: public class SmartPhone implements MusicPlayer { public void start() { System.out.println("start"); } public void stop() { System.out.println("stop"); } public void pause() { System.out.println("pause"); } }So now you have a good grasp of Java interfaces! Go learn about Abstract Classes to see how Java gives you yet another way to define contracts. Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started What is the correct way to implement an interface?To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
What is the correct way to implement an interface Mcq?Which of the following is the correct way of implementing an interface A by class B? Explanation: Concrete class implements an interface. They can be instantiated.
What is the correct way to inherit and implement the interface?Q) Which is the correct way to inherit and implement the interface? Consider and example, Interface is IAnimal and a class is Cat that wants to implement interface. Classes always implements an interface. An interface can extends another interface or multiple interfaces.
What kind of methods can be implemented in an interface?The interface body can contain abstract methods, default methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation).
|