接口是否比使用正确的方法更多 [英] Is there more to an interface than having the correct methods

查看:116
本文介绍了接口是否比使用正确的方法更多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想说我有这个界面:

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天全站免登陆