java请求接口示例_用示例解释Java接口

java请求接口示例

介面 (Interfaces)

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:

Java中的接口有点类似于Class,但是有一个显着的区别: interface 只能具有方法签名,字段和默认方法。 从Java 8开始,您还可以创建默认方法 。 在下一个块中,您可以看到接口的示例:

public interface Vehicle {
    public String licensePlate = "";
    public float maxVel
    public void start();
    public void stop();
    default void blowHorn(){
      System.out.println("Blowing horn");
   }
}

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.

上面的界面包含两个字段,两个方法和一个默认方法。 单独使用它并没有多大用处,但是它们通常与类一起使用。 怎么样? 很简单,您必须确保某些类可以implements它。

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.

一旦创建了implements任何接口的Java类,就可以将对象实例引用为接口的实例。 这个概念类似于继承实例化。

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

    即使省略了public关键字,Interface中的所有变量和方法都是公共的。

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

    如果一个类实现多个接口,则方法签名重叠的可能性很小。 由于Java不允许使用具有完全相同签名的多种方法,因此可能导致问题。 有关更多信息,请参见此问题

接口默认方法 (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.

在Java 8之前,我们无法指导Interface具有特定的方法实现。 如果突然更改接口定义,这会导致很多混乱和代码中断。

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!

幸运的是,Java 8现在为我们提供了接口的default方法。 default方法可以 直接在接口中包含其自己的实现! 因此,如果Class不实现默认方法,则编译器将采用Interface中提到的实现。 很好,不是吗? 因此,在您的库中,您可以在接口中添加任意数量的默认方法,而不必担心会破坏任何内容!

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:

很棒的问题。 在这种情况下,如果您未在Class中提供实现,则可怜的编译器会感到困惑,并且只会失败! 您还必须在Class中提供默认的方法实现。 还有一种使用super调用您喜欢的实现的好方法:

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.

Java 8的另一个新功能是可以向接口添加静态方法。 接口中的静态方法几乎与具体类中的静态方法相同。 唯一的不同是static方法不会在实现接口的类中继承。 这意味着在调用静态方法而不是实现它的类时,将引用该接口。

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:

在Java中,接口还可以通过使用您猜想的extends关键字来继承另一个接口:

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:

这意味着,类实现MusicPlayer接口必须实现的所有方法MusicPlayer以及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.

现在,您已经掌握了Java接口! 进一步了解抽象类,了解Java如何为您提供另一种定义合同的方式。

翻译自: https://www.freecodecamp.org/news/java-interfaces-explained-with-examples/

java请求接口示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值