gpt4 book ai didi

java - 在这个小程序中需要将类声明为 public 吗?

转载 作者:行者123 更新时间:2023-11-30 04:58:09 25 4
gpt4 key购买 nike

代码

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/* <applet code="tester" height=400 width=400>
* </applet>
*/

class tester extends JApplet {

boolean isFirst = true;

public void init() {

}

public void start() {
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent evt) {
half_tester(evt);
}
});
}

public void paint(Graphics g) {
if(isFirst) {
//JOptionPane.showMessageDialog(new JFrame(),"first time");
System.out.println("first time");
isFirst = false;
} else {
//JOptionPane.showMessageDialog(new JFrame(),"not the first time");
System.out.println("not the first time!");
}
}

public void half_tester(MouseEvent evt) {
repaint();
}
}

异常(exception)

load: tester is not public or has no public constructor.
java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class tester with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95)
at java.lang.Class.newInstance0(Class.java:366)
at java.lang.Class.newInstance(Class.java:325)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:795)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:724)
at sun.applet.AppletPanel.run(AppletPanel.java:378)
at java.lang.Thread.run(Thread.java:729)

为什么我需要将类声明为公共(public)?

最佳答案

Why do i need to declare the class public ?

因为其他包中的类(例如 sun.applet.AppletPanel)无法访问它。

如果您没有将 public 添加到您的类定义中,则仅其包可见,这是您案例中的默认包。

关于java - 在这个小程序中需要将类声明为 public 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7847489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com