当前页面: 开发资料首页 → J2SE 专题 → 这个小程序为什么可以直接调用setBackground方法和setForeground方法?
这个小程序为什么可以直接调用setBackground方法和setForeground方法?
摘要: 这个小程序为什么可以直接调用setBackground方法和setForeground方法?
大家好!在下面的程序中,我发现setBackground方法和setForeground方法在Componet类中才有,但
Sample 继承 Applet,Applet 继承 Panel,Panel继承Container,Container继承Componet,
这两个方法为什么可以直接调用呢?而我下面第二个自己写的测试程序怎么就不能直接进行类似的调用??
import java.awt.*;
import java.applet.*;
public class Sample extends Applet{
String msg;
public void init(){
setBackground(Color.cyan);
setForeground(Color.red);
msg="Inside init()--";
}
public void start(){
msg+="Indide start()--";
}
public void paint(Graphics g){
msg+="Inside paint()";
g.drawString(msg,10,30);
}
}
测试程序:
abstract class A{
abstract void callme();
void callMeToo(){
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme(){
System.out.println("B's implementatioin of callme");
}
}
public class AbstractDemo extends B{
public static void main(String[] args) {
//B b=new B();
callMeToo();
System.out.println("B's implementatioin of callme");
}
}
静态方法不能直接调用非静态方法。
你可以将程序改为:
public static void main(String[] args) {
AbstractDemo b= new AbstractDemo ();
b.callMeToo();
System.out.println("B's implementatioin of callme");
}
恩,楼上的说对了,我这里再解释详细一些:
因为静态的成员或方法,在对象初始化之前已经存在,而非静态的成员或方法要在产生对象后才存在于对象中,因此静态方法不能直接调用非静态方法,上面的main方法是static (静态)的,所以...
觉得解释得还可以,就给点分吧~~哈哈
不知道这么说合不合适:
静态方法是某个"类"的:
如调main()可以这样:AbstractDemo .main(null);
不用生成对象,直接拿过来用就行了。
非静态方法是"类"对应的"对象"的:
如要调setBackground():Panel panel = new Panel();
panel.setBackground();
得先生成一个对象.