简体   繁体   English

为什么是 super.paint(g) 而不是 this.paint(g)?

[英]Why is it super.paint(g) and not this.paint(g)?

Just a theoretical question about inheritance.只是一个关于 inheritance 的理论问题。

So let's say I've got a class "GamePanel" which extends JPanel.因此,假设我有一个扩展 JPanel 的 class“GamePanel”。

I know within the class, if I call super.paint(g) , it will call the parent class (JPanel) paint method.我知道在 class 中,如果我调用super.paint(g) ,它将调用父级 class (JPanel) 绘制方法。

But if I create an object GamePanel, shouldn't it already inherit all of JPanels methods?但是如果我创建一个 object GamePanel,它不应该已经继承了所有 JPanels 方法吗? So in that case, why doesn't this.paint(g) work?那么在那种情况下,为什么this.paint(g)不起作用? The current object should be able to access that method right?现在的object应该可以访问那个方法吧?

If not, why does this.setBackgroundColor(...) work?如果不是,为什么this.setBackgroundColor(...)起作用?

Because apparently this.setBackgroundColor(...) works as well as super.setBackGroundColor(...) .因为显然this.setBackgroundColor(...)super.setBackGroundColor(...)一样有效。 So it's almost like "super" can access all the methods while "this" can't?所以这几乎就像“super”可以访问所有方法而“this”不能?

It matters if you've redefined paint in the child class...you need a way within your paint method to call the ancestor paint method, otherwise it could only "call itself" like recursively from within that method...如果您在子 class 中重新定义了paint ,这很重要...您需要在paint方法中使用一种方法来调用祖先paint方法,否则它只能像从该方法中递归地“调用自身”一样...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM