java的优缺点 以及它用于什么,Java中的接口 - 它们用于什么?
发布日期:2022-03-15 11:49:58 浏览次数:10 分类:技术文章

本文共 2647 字,大约阅读时间需要 8 分钟。

I just started learning Java not so long ago.

I've come across Interfaces which I know how to use but still can't quite grasp the idea of it.

As I understand it, interfaces are usually implemented by classes, which then have to implement the methods declared in the interface.

The problem is - what exactly is the point? Wouldn't it be easier to just implement the methods from the interface as normal class methods? What exactly are the advantages of using interfaces?

I've tried looking for an answer on google. There were many but I still couldn't understand the point of it. I also read this question and its answers, but the whole contract thing just makes it more complicated...

Hopefully someone could simplify it good enough! :)

Thanks in advance!


An interface allows you to provide a different implementation at runtime, inject dependencies, separate concerns, use different implementations for testing.

Just think of an interface as a contract that a class guarantees to implement. The concrete class that implements the interface is irrelevant. Don't know if this helps.

Figured some code might help. This doesn't explain everything there is more to interfaces, keep reading but I hope this gets you started. Point here is that you can vary the implementation...

package stack.overflow.example;

public interface IExampleService {

void callExpensiveService();


public class TestService implements IExampleService {


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 {


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();


// Alternatively, in a real program I might write

IExampleService testService = new ExpensiveService();


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



转载地址: 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

下一篇:一级计算机考试计算,全国计算机一级MS OFFICE等级考试计算题(3)



[***.191.171.7]2022年08月17日 09时18分54秒


-- 愿君每日到此一游!