我正在查看applet代码并且让我感到震惊。
我的问题:
为什么setForeground()
在没有对象的情况下使用,尽管它被定义为API中的非静态方法
代码如下:
import java.applet.Applet;
import java.awt.*;
/*<applet code = "swings.class" height = "500" width = "500"></applet>*/
public class Swings extends Applet{
public void init(){
setBackground(Color.yellow);
setForeground(Color.red);
Font f = new Font("Comic Sans MS",Font.BOLD,25);
setFont(f);
}
public void paint(Graphics g){
g.drawString("Welcome to Applets",100,100);
}
}
答案 0 :(得分:0)
setForeground
在public
中声明为Component
,Swings
是Component
的子类,
这意味着setForeground
将Swings
作为自己的类成员继承,因此您可以直接在setForeground
中调用Swings
。
您可以查看jls了解详情。
<强>更新强>
在java中,如果两个非静态方法都在同一个类中,它们可以直接相互调用,而无需创建新实例。
由于setForeground
继承了Swings
,setForeground
和init
都是类Swings
的成员。因此,您可以直接在setForeground
中致电init
。