Clayton Clark
Clayton Clark

Reputation: 1

Attaching class to another main class in java

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.

Upvotes: 0

Views: 152

Answers (3)

kosa
kosa

Reputation: 66647

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{
  ..........
}

Upvotes: 1

hlopko
hlopko

Reputation: 3270

If you need single .java file, you can declare second class private withing main class, or have it next to the main class in file without 'public' modifier. Your file would look like this:

public class Main {
    //...
}

class Inner {
    //...
}

However, if you need a single .class file (compiled .java file), I have bad news for you, it cannot be done, Java compiler always generates one .class file per class. Now it depends on how big of a trouble would it be to rewrite your program to be a single class, or compile the second one locally, get bytes, store them statically in main class, and use class loader to load the bytes in runtime.. Which sounds pretty funny to me :)

Upvotes: 0

duffymo
duffymo

Reputation: 308848

One public class per file, and the class name must match the file name.

But you can have as many package private classes as you wish. Put the main method in the public class.

For example, in Foo.java:

public class Foo {
}

class Bar {
}

class Baz {
}

Upvotes: 1

Related Questions