Java接口-它们的作用是什么?

Asaf:

可能重复:
接口的作用继续

我不久前才开始学习Java。
我遇到过Interfaces我知道如何使用它,但仍然不太了解它的想法。
据我了解,interfaces通常是由类实现的,然后必须实现在接口中声明的方法。
问题是-真正的意义是什么?仅将接口中的方法实现为普通的类方法会更容易吗?使用接口的确切优势是什么?

我尝试在Google上寻找答案。有很多,但我仍然不明白它的意义。我也阅读了这个问题及其答案,但是整个合同的事情使它变得更加复杂。

希望有人可以简化它!:)
预先感谢!

0909EM:

接口允许您在运行时提供不同的实现,注入依赖项,单独的关注点,使用不同的实现进行测试。

只需将接口视为类保证实现的契约即可。实现该接口的具体类无关紧要。不知道这是否有帮助。

想出一些代码可能会有所帮助。这并不能解释界面的所有内容,请继续阅读,但我希望这可以帮助您入门。这里的重点是您可以更改实现...

package stack.overflow.example;

public interface IExampleService {
void callExpensiveService();
}

public class TestService implements IExampleService {

@Override
public void callExpensiveService() {
    // This is a mock service, we run this as many 
    // times as we like for free to test our software

}
}

public class ExpensiveService implements IExampleService {
@Override
public void callExpensiveService() {
    // This performs some really expensive service,
    // Ideally this will only happen in the field
    // We'd rather test as much of our software for
    // free if possible.
}
}


public class Main {

/**
 * @param args
 */
public static void main(String[] args) {

    // In a test program I might write
    IExampleService testService = new TestService();
    testService.callExpensiveService();

    // Alternatively, in a real program I might write
    IExampleService testService = new ExpensiveService();
    testService.callExpensiveService();

    // The difference above, is that we can vary the concrete 
    // class which is instantiated. In reality we can use a 
    // service locator, or use dependency injection to determine 
    // at runtime which class to implement.

    // So in the above example my testing can be done for free, but 
    // real world users would still be charged. Point is that the interface
    // provides a contract that we know will always be fulfilled, regardless 
    // of the implementation. 

}

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章