java – 类无法实例化

我有java applet和图形的问题.我试图在Eclipse中运行它,它失败了.
我是java的新手,我希望你能帮助我.
我有两个文件:Say.java和SayWhat.java.
Say.java:

public class Say {
    SayWhat word = new SayWhat("Hello World");

}

SayWhat.java:

import java.applet.Applet;
import java.awt.Graphics;

@SuppressWarnings("serial")
public class SayWhat extends Applet {
     Graphics g;
     String what;
    public SayWhat(String what) {
        this.what=what;
    }
    public void paint(Graphics g){
        g.drawString(what, 20, 20);
    }
}

出现的错误是:

load: SayWhat.class can't be instantiated.
java.lang.InstantiationException: SayWhat
    at java.lang.Class.newInstance0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at sun.applet.AppletPanel.createApplet(Unknown Source)
    at sun.applet.AppletPanel.runLoader(Unknown Source)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

你能告诉我我做错了什么吗?

解决方法:

applet需要有一个公共的无参数构造函数(通过具有显式的公共no-arg构造函数,或者根本没有显式构造函数;在后一种情况下,编译器将提供一个公共的无参数构造函数作为默认值).你的类的唯一构造函数需要参数:

public SayWhat(String what) {

因此,如果没有该参数,则无法实例化类,因此不能将其用作applet.

上一篇:如何在网页中嵌入Java小程序?


下一篇:java 面试经典题