如何在没有在java中创建实例的情况下调用setForeground方法?

时间:2018-03-17 12:27:48

标签: java class static applet

我正在查看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);
    }
}

1 个答案:

答案 0 :(得分:0)

setForegroundpublic中声明为ComponentSwingsComponent的子类,

enter image description here

这意味着setForegroundSwings作为自己的类成员继承,因此您可以直接在setForeground中调用Swings

您可以查看jls了解详情。

<强>更新

在java中,如果两个非静态方法都在同一个类中,它们可以直接相互调用,而无需创建新实例。

由于setForeground继承了SwingssetForegroundinit都是类Swings的成员。因此,您可以直接在setForeground中致电init