除了拥有正确的方法之外,接口还有更多的意义吗? [英] Is there more to an interface than having the correct methods

查看:25
本文介绍了除了拥有正确的方法之外,接口还有更多的意义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以假设我有这个界面:

So lets say I have this interface:

public interface IBox
{
   public void setSize(int size);
   public int getSize();
   public int getArea();
  //...and so on
}

我有一个实现它的类:

public class Rectangle implements IBox
{
   private int size;
   //Methods here
}

如果我想使用 IBox 接口,我实际上无法创建它的实例,方式如下:

If I wanted to use the interface IBox, i can't actually create an instance of it, in the way:

public static void main(String args[])
{
    Ibox myBox=new Ibox();
}

对吧?所以我实际上必须这样做:

right? So I'd actually have to do this:

public static void main(String args[])
{
    Rectangle myBox=new Rectangle();
}

如果这是真的,那么接口的唯一目的是确保实现接口的类具有接口描述的正确方法?或者接口还有其他用途吗?

If that's true, then the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?

推荐答案

接口是使您的代码更加灵活的一种方式.你要做的是:

Interfaces are a way to make your code more flexible. What you do is this:

Ibox myBox=new Rectangle();

然后,如果您决定要使用不同类型的框(也许还有另一个库,具有更好类型的框),则将代码切换为:

Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:

Ibox myBox=new OtherKindOfBox();

一旦习惯了,您就会发现这是一种很棒(实际上必不可少)的工作方式.

Once you get used to it, you'll find it's a great (actually essential) way to work.

另一个原因是,例如,如果您想创建一个框列表并对每个框执行一些操作,但您希望列表包含不同类型的框.在每个盒子上你可以这样做:

Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:

myBox.close()

(假设 IBox 有 close() 方法)即使 myBox 的实际类会根据您在迭代中所处的框而变化.

(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.

这篇关于除了拥有正确的方法之外,接口还有更多的意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆