困惑什么是“超级”?关键字在这种情况下正在做
我还在努力学习java,如果我错了,请纠正我。 据我了解, super 关键字调用类的构造函数。所以我不明白说的意义
super.paint(g)
是什么,或者最近在阅读动画时我遇到了
super.addNotify()
我尝试查找关于两者的文档(可能很差),但它并没有充分满足我的好奇心,所以我们在这里。
对这两个示例或一般情况的任何澄清将不胜感激。谢谢!
I am still trying to learn java, so correct me if I'm wrong.
As I understand it, the super keyword calls the constructor of a class. So I do not understand what the significance of saying
super.paint(g)
does for example, or more recently while reading about animation I came across
super.addNotify()
I tried looking up documentation on the two (perhaps poorly) and it didn't satisfy my curiosity adequately, so here we are.
Any clarification on those two example or in general would be appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
super
是一个关键字,它是对您使用该关键字的类的超类的引用。因此,
super()
调用超类的构造函数,super(x)
调用参数化构造函数,super.paint(g)
调用超类的paint()
方法。super
is a keyword that is a reference to the superclass of the class from which you are using the keyword.So
super()
calls the constructor of the superclass,super(x)
calls a parameterised constructor, andsuper.paint(g)
calls thepaint()
method of the superclass.不,super关键字指的是基类。所以 super.f() 调用超类的 f() 方法。
在某些情况下,超类提供一些基本例程,当您重写该函数时,您首先调用基类的实现,然后添加自定义代码。你的两个例子都是这种情况。
No, the super keyword refers to the base class. So super.f() calls the f() method of the superclass.
In some cases, the superclass privides some basic routines, and when you override the function, you first call the base class's implementation, and then add your custom code. It's the case for both your examples.
让我用代码来描述一下:
Let me describe it in code:
所有其他答案都非常清楚。但也许你想知道为什么有人会调用 super。
Java 有一个继承系统,通过该系统,您可以从另一个类派生一个类,即从一个类中获取行为和数据结构,然后在另一个类中重用它。这里的关键是(或者是,当它被构思时)是重用已经编写的代码,并以某种方式扩展它。
All the other answers are pretty clear. But maybe you would like to know why in the first place someone would call super.
Java have an inheritance system, by whom you may derive a class from another, i.e. take the behaviuor and data structures from a class and reuse it in another. The key here is (or was, when it was conceived) is to reuse code you have already written, and extend it in some way.