无需类的 Java2D 方法调用
我刚刚开始学习Java并尝试绘制一些矩形。
我已经运行 this 示例并且无法理解一件事: ShapesDemo2D 类有一个构造函数:
public void init() {
//Initialize drawing colors
setBackground(bg);
setForeground(fg);
}
我知道 setBackground
是一个方法。
- 但如果没有类或实例引用,如何调用它呢?
这是 Component.java 文件中抽象 Component 类的方法。
- 它不应该像
Component.setBackground(bg)
或componentInstance.setBackground(bg)
吗?
但Component是一个抽象类,因此它不能被实例化,也不能调用它的方法。
- 那么如何才能调用这个方法呢?
I just started to learn Java and tried to draw some rectangles.
I have run this example and can't understand one thing:
class ShapesDemo2D has a constructor:
public void init() {
//Initialize drawing colors
setBackground(bg);
setForeground(fg);
}
I understand that setBackground
is a method.
- But how can it be called without a class or instance reference?
This is a method of an abstract Component class in Component.java file.
- Shouldn't it be like
Component.setBackground(bg)
orcomponentInstance.setBackground(bg)
?
But Component is an abstract class, so it can't be instantiated, and it's methods can not be called.
- So how it is possible to call this method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您忘记了类代码顶部的
ShapesDemo2D extends JApplet
这意味着该类扩展了另一个类 JApplet,因此上述方法中的代码实际上是有效的调用super.setBackground(bg);
和super.setForeground(fg);
。超类 JApplet 具有这些方法,因为根据 JApplet API,该类继承自具有这些方法的 Component,这意味着 ShapesDemo2D 也将继承这些方法。话虽如此,请放弃本教程,因为小程序不再受支持,是死技术,并且已经死了很长时间,并且学习死技术没有任何意义。
旁注,你说:
但这实际上不是构造函数,而是一个方法。 ShapesDemo2D 类的构造函数如下所示:
这可能看起来像是一种迂腐的区别,但编程就是要尽可能准确地表达您的想法和代码。 Java 编译器是严格且无情的,因此您也必须如此。
You're forgetting
ShapesDemo2D extends JApplet
at the top of the class code which means that the class extends another class, JApplet, and so the code in the method above above is effectively callingsuper.setBackground(bg);
andsuper.setForeground(fg);
. The super class, JApplet has these methods since as per the JApplet API, the class extends from Component which has these methods, meaning that ShapesDemo2D will have inherited the methods as well.Having said this, please ditch this tutorial since applets are no longer support, are dead technology and have been dead for the longest time, and there is no sense learning a dead technology.
Side note, you state:
But this is in fact not a constructor but rather a method. A constructor for the ShapesDemo2D class would look like:
This may seem like a pedantic distinction, but programming is all about being as accurate as possible with your thinking and your code. The Java compiler is strict and unforgiving, and so you must be as well.