gpt4 book ai didi

java - 为什么 addMouseListener 方法不需要 super ?

转载 作者:行者123 更新时间:2023-12-02 03:12:25 25 4
gpt4 key购买 nike

我的问题是,当我创建一个继承自 JPanel 的类时,为什么不使用 super.addMouseListener() 来添加监听器?我认为这个方法位于父类(super class) JPanel 中。这是代码:

private class DrawPanel extends JPanel
{
private int prefwid, prefht;

// Initialize the DrawPanel by creating a new ArrayList for the images
// and creating a MouseListener to respond to clicks in the panel.
public DrawPanel(int wid, int ht)
{
prefwid = wid;
prefht = ht;

chunks = new ArrayList<Mosaic>();

// Add MouseListener to this JPanel to respond to the user
// pressing the mouse. In your assignment you will also need a
// MouseMotionListener to respond to the user dragging the mouse.
addMouseListener(new MListen());
}

最佳答案

因为没有必要。

您没有在 DrawPanel 类中声明方法 addMouseListener,因此编译器会检查父类(super class)中是否有此类方法,并在 java.awt 中找到它.组件。由于此方法是由 DrawPanel 类继承的,因此可以在此处调用它。

如果您想了解更深入的原因,您需要阅读JLS Sec 15.12, "Method Invocation Expressions" 。然而,这并不完全是轻松阅读。

我认为关键的句子是:

Sec 15.12.1

For the class or interface to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation:

  • If the form is MethodName, that is, just an Identifier, then:

    • If the Identifier appears in the scope of a visible method declaration with that name (§6.3, §6.4.1), then:
    • If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.
    • ...

所以TDrawPanel

Sec 15.12.2.1

The class or interface determined by compile-time step 1 (§15.12.1) is searched for all member methods that are potentially applicable to this method invocation; members inherited from superclasses and superinterfaces are included in this search.

因此,在 DrawPanel 及其所有父类(super class)中搜索名为 addMouseListener 的方法。

关于java - 为什么 addMouseListener 方法不需要 super ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com