Using interface methods java

Java Interface

Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely «abstract class» that is used to group related methods with empty bodies:

Example

// interface interface Animal < public void animalSound(); // interface method (does not have a body) public void run(); // interface method (does not have a body) >

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:

Example

// 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 Main < public static void main(String[] args) < Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); >> 

Notes on Interfaces:

  • Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an «Animal» object in the MyMainClass)
  • Interface methods do not have a body — the body is provided by the «implement» class
  • On implementation of an interface, you must override all of its methods
  • Interface methods are by default abstract and public
  • Interface attributes are by default public , static and final
  • An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

1) To achieve security — hide certain details and only show the important details of an object (interface).

2) 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 Interfaces

To implement multiple interfaces, separate them with a comma:

Example

interface FirstInterface < public void myMethod(); // interface method >interface SecondInterface < public void myOtherMethod(); // interface method >class DemoClass implements FirstInterface, SecondInterface < public void myMethod() < System.out.println("Some text.."); >public void myOtherMethod() < System.out.println("Some other text. "); >> class Main < public static void main(String[] args) < DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); >> 

Источник

Interfaces

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a «contract» that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group’s code is written. Generally speaking, interfaces are such contracts.

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group’s software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.

Читайте также:  React css modules scss

Interfaces in Java

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.

Defining an interface is similar to creating a new class:

public interface OperateCar < // constant declarations, if any // method signatures // An enum with values RIGHT, LEFT int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); . // more method signatures >

Note that the method signatures have no braces and are terminated with a semicolon.

To use an interface, you write a class that implements the interface. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. For example,

public class OperateBMW760i implements OperateCar < // the OperateCar method signatures, with implementation -- // for example: public int signalTurn(Direction direction, boolean signalOn) < // code to turn BMW's LEFT turn indicator lights on // code to turn BMW's LEFT turn indicator lights off // code to turn BMW's RIGHT turn indicator lights on // code to turn BMW's RIGHT turn indicator lights off >// other members, as needed -- for example, helper classes not // visible to clients of the interface >

In the robotic car example above, it is the automobile manufacturers who will implement the interface. Chevrolet’s implementation will be substantially different from that of Toyota, of course, but both manufacturers will adhere to the same interface. The guidance manufacturers, who are the clients of the interface, will build systems that use GPS data on a car’s location, digital street maps, and traffic data to drive the car. In so doing, the guidance systems will invoke the interface methods: turn, change lanes, brake, accelerate, and so forth.

Interfaces as APIs

The robotic car example shows an interface being used as an industry standard Application Programming Interface (API). APIs are also common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product. An example would be a package of digital image processing methods that are sold to companies making end-user graphics programs. The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company’s API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.

Читайте также:  Css точка по центру

Источник

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!

Читайте также:  Processing using java library

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.

Источник

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