-3

一个接口有多少种方法是理想的数量?你怎么知道一个接口从一个实现中有多少方法?那么 Mouselistener 接口会有 5 个方法吗?

   // ToggleButton Listener Class:
    class ToggleButton implements MouseListener {

            public void mousePressed(MouseEvent e) { }

            public void mouseReleased(MouseEvent e) { }

            public void mouseEntered(MouseEvent e) { }

            public void mouseExited(MouseEvent e) { }

            public void mouseClicked(MouseEvent e) {
               // e.getButton() returns 0, 1, 2, or 3, where 1 is the
               // left mouse button and 3 is the right mouse button:
               mousebutton = e.getButton();

               // Identify which JButton was clicked on by getting the
               // source of the event e; Book, p. 484 (Event and Event
               // Source);
               // e.getSource() returns an object of the Object
               // superclass, and that object has to be cast to a
               // JButton with (JButton):
               JButton B = (JButton)e.getSource();
               nextSymbol( B );
            }

    } // end ToggleButton class
4

3 回答 3

0

好吧,您可以先查看文档并计算那里的方法数量,注意从它的 super interface中获取任何方法。

一个接口有多少种方法是理想的数量?

需要多少就多少,不多也不少。听起来很颠倒,但事实并非如此:答案确实取决于它。一些接口没有定义(是的,没有;参见EventListener)或一种方法,其他接口定义了许多方法。两者都有意义。

你怎么知道一个接口从一个实现中有多少方法?

您不能,因为在实现接口的类中定义的某些方法可能特定于该类而不是接口。

那么 Mouselistener 接口会有 5 个方法吗?

看文档,是的。

于 2013-07-09T00:57:15.113 回答
0

没有理想的数字。这取决于相关的接口。

例如,Runnable有一个重要的方法,void run()List有[相当多的[(http://docs.oracle.com/javase/6/docs/api/java/util/List.html)。甚至没有,并且仅在标记接口Serializable的精神中充当语义标记。

前者是作为对象动态给出的方法的轻量级包装器,而后者是列表应该能够做什么的相当广泛的契约。

您需要做的就是声明您需要的方法,并忽略您不需要的方法。

创建自己的时,您始终可以扩展。例如,BasicClickListener可以监听点击,而ExtendedClockListenerwhich extendsBasicClickListener也可以处理拖动和鼠标悬停。

官方的 MouseListener 为五个

于 2013-07-09T00:57:40.463 回答
0

您可以通过一点反射来检索接口(或类)上的方法数量。ToggleButton可以通过定义如下方法反射性地获取可用的类数

        public void countInterfaceMethods(){
          //this will get an array of all the interfaces your class implements
          Class<?>[] clazz =    this.getClass().getInterfaces(); 
          //retrieve only the first element of the array, because ToggleButton implements only one interface
          Class<?> theFirstAndOnlyInterface = clazz[0]; 
          //get all the methods on that interface
          Method[] theArrayOfMethods = theFirstAndOnlyInterface .getMethods(); 
          //get the length of the array. This is the number of methods in that interface
          int numberOfMethods = theArrayOfMethods.length;

        }

如您所见,从技术上讲,这是可行的。但仅仅因为某件事是可行的,并不意味着它就应该去做

于 2013-07-09T01:08:05.667 回答