在 java 中如何在不创建实例的情况下调用 setForeground 方法?
How is setForeground method called without creating instance in java?
我在看一个小程序代码,它让我印象深刻。
我的问题:
为什么 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);
}
}
setForeground
在 Component
中声明为 public
,Swings
是 Component
的子 class,
表示setForeground
会被Swings
继承为自己的class成员,所以可以直接在Swings
中调用setForeground
您可以查看 jls 了解更多详情。
更新
在java中,如果两个non-static方法在同一个class中,它们可以直接相互调用,无需创建新实例。
由于setForeground
被Swings
继承,setForeground
和init
都是classSwings
的成员。所以你可以直接在init
中调用setForeground
。
我在看一个小程序代码,它让我印象深刻。
我的问题:
为什么 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);
}
}
setForeground
在 Component
中声明为 public
,Swings
是 Component
的子 class,
表示setForeground
会被Swings
继承为自己的class成员,所以可以直接在Swings
中调用setForeground
您可以查看 jls 了解更多详情。
更新
在java中,如果两个non-static方法在同一个class中,它们可以直接相互调用,无需创建新实例。
由于setForeground
被Swings
继承,setForeground
和init
都是classSwings
的成员。所以你可以直接在init
中调用setForeground
。