Can two classes exist in a single .java file?
Reply quick, please.

Recommended Answers

All 8 Replies

Can two classes exist in a single .java file?
Reply quick, please.

Yes they can...

you can have unlimited classes in one file, but you can only have one public class in one file, and this class needs to have the same name as the Java file.

you can have unlimited classes in one file, but you can only have one public class in one file, and this class needs to have the same name as the Java file.

Public??
But the book I'm learning from has more than one public classes. I have attached the two pages I want to show you. It is a little difficult to read, but open it up (Right click --> Open with --> Paint) with Paint. Thank you.

that's not in one java file.
they print the code after each other, but they assume you know where the new file starts.

you mean :-
the first class-one file
and so on?

if so, which one am i supposed to compile and run with javac and java?

You compile in the order of depenedency, I'm not sure if javac handles that in some way, try it or google.

If ClassA depends on ClassB, compile ClassA first and then ClassB.

To run you need your main class, i.e. the class where you have the method "public static void main(int[] args)", if that is ClassB then you write...

java ClassB

Thank you! I am closing this thread.

Further doubts of mine ( I'm a newbie **:-(** ) will be discussed in other threads.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.