0

I'm creating an applet so I decided to use two classes, but then I was asked to have a single java file. Could I add my other class to the main class? If so, how? I tried declaring my secondary class private, but it didn't work.

4

3 回答 3

1

Just declare your another class right after your main class without any modifier (assuming you want it as separate detached class). Otherwise, Nested Classes (or) annonymous classes may be the way to go.

Example:

Your file name is Hello.java

public class Hello{
  .........
}

class AnotherClass{
  ..........
}
于 2012-10-09T15:31:45.173 回答
1

每个文件一个公共类,并且类名必须与文件名匹配。

但是您可以拥有任意数量的包私有类。将 main 方法放在公共类中。

例如,在 Foo.java 中:

public class Foo {
}

class Bar {
}

class Baz {
}
于 2012-10-09T15:33:03.107 回答
0

如果您需要单个 .java 文件,您可以在主类中声明第二类私有,或者将其放在文件中的主类旁边而不使用“public”修饰符。您的文件将如下所示:

public class Main {
    //...
}

class Inner {
    //...
}

但是,如果您需要一个 .class 文件(编译后的 .java 文件),我要告诉您一个坏消息,它无法完成,Java 编译器总是为每个类生成一个 .class 文件。现在取决于将程序重写为单个类,或者在本地编译第二个,获取字节,将它们静态存储在主类中,并使用类加载器在运行时加载字节会有多大的麻烦。 . 这对我来说听起来很有趣:)

于 2012-10-09T15:39:38.933 回答