简体   繁体   中英

Implementing Java interfaces and methods

I'm learning about Java interfaces and method writing. 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 .

The interface need not use the public keyword; all the methods in an interface are public by default.

use implements keyword in your class declartion to implement an interface

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

Example - public class TestClass implements 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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