Calling interface methods in java

How to call an interface method in Java?

In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object.

Example

public interface InterfaceDemo < default public void displayNameDefault(String name)< System.out.println("Your name is : " + name); >public void displayName(String name); public void displayNameAndDesignation(String name, String designation); >

The above interface defines three methods for displaying a name and optionally a job title. One method is a default method that contains implementation logic. The remaining two methods do not include implementation logic.

public class InterfaceDemoImpl implements InterfaceDemo < public void displayName(String name) < System.out.println(name); >public void displayNameAndDesignation(String name, String designation) < System.out.println("Name:" + name + "\n"+ "Designation:" + designation); >>

The above java program declares that it will implement the interface by using the implements keyword. The program is now obligated to provide java code for the two non-default methods. Accordingly, implementations of the methods are provided.

public class CallInterfaceMethod < public static void main(String args[])< InterfaceDemo demo = new InterfaceDemoImpl(); demo.displayName("Adithya"); demo.displayNameAndDesignation("Adithya", "Java Developer"); demo.displayNameDefault("Adithya"); >>

The above program instantiates the interface implementation. Next, each of the methods defined in the interface is called.

Output

Adithya Name:Adithya Designation:Java Developer Your name is : Adithya

Источник

How to Call an Interface Method in Java

In order to call an interface method from a Java program, the program must first instantiate the interface implementation program. A method can then be called using the implementation object. To learn how to call an interface method in Java, follow these 10 steps.

  1. Open your text editor and type in the following Java statements:Java Source for Interface DefinitionThe interface defines three methods for displaying a name and optionally a job title. One method is a default method that contains implementation logic. The remaining two methods do not include implementation logic.
  2. Save your file as CreateAnInterfaceDefinition.java .
  3. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .Compile Source for Interface DefinitionThe interface is now ready to be implemented by a Java program.
  4. Open your text editor and type in the following Java statements:Java Source for Interface ImplementationThe Java program declares that it will implement the interface by using the implements keyword. The program is now obligated to provide Java code for the two non-default methods. Accordingly, implementations of the methods are provided.
  5. Save your file as CreateAnInterfaceDefinitionImpl.java . The suffix Impl is a standard way of advertising that this Java program is an implementation of CreateAnInterfaceDefinition.java .
  6. In your command prompt, navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .Compile Source for Interface ImplementationThe interface implementation can now be instantiated by a Java class so that the methods can be called.
  7. Return to your text editor. You will now type in the Java statements for the program that calls the interface methods:Java Source for Calling Interface MethodsThe program instantiates the interface implementation. Next, each of the methods defined in the interface is called.
  8. Save your file as CallAnInterfaceMethod.java .
  9. Return to the command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .Compile Source for Calling Interface Implementation
  10. Type in the command to run your program and hit Enter .Run for Interface ImplementationThe output demonstrates that each interface method has been called.
Читайте также:  Php удаление пустых элементов массива
  1. How to Check Object Type in Java
  2. How to Create a Jar File in Java
  3. How to Compile Packages in Java
  4. How to Throw an Exception in Java
  5. How to Create an Exception Class in Java
  6. How to Use the super Keyword to Call a Base Class Constructor in Java
  7. How to Use the Comparator.comparing Method in Java 8
  8. How to Use System.in in Java
  9. How to Call an Interface Method in Java (this article)
  10. How to Add a Time Zone in the Java 8 Date/Time API
  11. How to Rethrow an Exception in Java
  12. How to Use the instanceof Operator with a Generic Class in Java
  13. How to Instantiate an Object in Java
  14. How to Filter Distinct Elements from a Collection in Java 8
  15. How to Create a Derived Class in Java
  16. How to Skip Elements with the Skip Method in Java 8
  17. How to Create a Java Bean
  18. How to Implement an Interface in Java
  19. How to Compare Two Objects with the equals Method in Java
  20. How to Set PATH from JAVA_HOME
  21. How to Prevent Race Conditions in Java 8
  22. How to Write a Block of Code in Java
  23. How to Display the Contents of a Directory in Java
  24. How to Group and Partition Collectors in Java 8
  25. How to Create a Reference to an Object in Java
  26. How to Reduce the Size of the Stream with the Limit Method in Java 8
  27. How to Write an Arithmetic Expression in Java
  28. How to Format Date and Time in the Java 8 Date/Time API
  29. How to Use Comparable and Comparator in Java
  30. How to Break a Loop in Java
  31. How to Use the this Keyword to Call Another Constructor in Java
  32. How to Write a Unit Test in Java
  33. How to Declare Variables in Java
  34. How to Override Base Class Methods with Derived Class Methods in Java
  35. How to Use Serialized Objects in Java
  36. How to Write Comments in Java
  37. How to Implement Functional Interfaces in Java 8
  38. How to Write Type Parameters with Multiple Bounds in Java
  39. How to Add Type and Repeating Annotations to Code in Java 8
  40. How to Use Basic Generics Syntax in Java
  41. How to Map Elements Using the Map Method in Java 8
  42. How to Work with Properties in Java
  43. How to Write while and do while Loops in Java
  44. How to Use the finally Block in Java
  45. How to Write for-each Loops in Java
  46. How to Create a Method in Java
  47. How to Continue a Loop in Java
  48. How to Handle Java Files with Streams
  49. How to Create an Interface Definition in Java
  50. How Default Base Class Constructors Are Used with Inheritance
Читайте также:  Python requests send files

Training Options

Course Catalog

Источник

Interfaces

Java Interfaces Explained with Examples

Java Interfaces Explained with Examples

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 Interface

Once 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

  • You can place variables within an Interface, although it won’t be a sensible decision as Classes are not bound to have the same variable. In short, avoid placing variables!
  • All variables and methods in an Interface are public, even if you leave out the public keyword.
  • An Interface cannot specify the implementation of a particular method. Its up to the Classes to do it. Although there has been a recent exception (see below).
  • If a Class implements multiple Interfaces, then there is a remote chance of method signature overlap. Since Java does not allow multiple methods of the exact same signature, this can lead to problems. See this question for more info.

Interface Default Methods

Before 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 MusicPlayer

Static Methods in Interfaces

Also 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 Interface

It 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.

Источник

Оцените статью