简体   繁体   English

实现Java接口和方法

[英]Implementing Java interfaces and methods

I'm learning about Java interfaces and method writing. 我正在学习Java接口和方法编写。 I'm wondering how you would create a class that uses this interface? 我想知道如何创建使用此接口的类? Also what are the best ways to implement the methods it includes? 另外,实现其中包括的方法的最佳方法是什么? At the moment, i'm trying to learn different ways for writing methods. 目前,我正在尝试学习编写方法的不同方法。 Thanks in advance for your help :) 在此先感谢您的帮助 :)

interface Dealer {

    void assignPlayers(ArrayList<Player> p);

    ...

    public void settleBets();
} 

It's simple: 这很简单:

public class BakratDealer implements Dealer {
    // implement all the methods here
}

It's not about the best way; 这不是最好的方法。 this is the only way. 这是唯一的方法。 You must either implement all the methods in the interface or declare the class abstract . 您必须在接口中实现所有方法或声明类abstract

The interface need not use the public keyword; 接口不必使用public关键字; all the methods in an interface are public by default. 默认情况下,接口中的所有方法都是公共的。

use implements keyword in your class declartion to implement an interface 在类声明中使用implements关键字来实现接口

public class YourClass implements Dealer {

 //implement all your method defined in the interface here
}

You can implement the class the same way you inherit another class except you use the word "implements" instead of "extends". 您可以使用继承另一个类的相同方法来实现该类,除了使用单词“ implements”而不是“ extends”。

Example - public class TestClass implements Dealer { } 示例-公共类TestClass实现Dealer {}

In the class that is using the implementation, you write the methods just as you would write any other method. 在使用实现的类中,您将编写方法,就像编写任何其他方法一样。 You just have to be sure to implement ALL the methods from the interface or the class has to be an abstract class. 您只需要确保从接口实现所有方法,否则该类必须是抽象类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM