Multiple Classes in one file?
First off !! Sorry to keep on bugging so many on such, im sure to be, tedious beginner questions.
Is it possible in java to define multiple classes in one source file? If so how would i add it to something like this Code:
//main class |
Public class name == file name. Java's 'feature'. You can add private classes, however.
|
Quote:
---FileName MyProject.java-- Class MyProject { public static void main( String[] args) { //some stuff here } } private class PClass { //methods and all that good stuff } And then from the main MyProject method use the defined bellow classes by class.object() after creating instances in my main method? |
I don't know if the method you proposed work, but actually i do it another way!
eg: filename = Project1.java Code:
public class Project1 1 - Project1.class 2 - Project1$SubClass1.class |
Its sufficient if you declare the driver class, the class which is going to be used for the compilation and execution as public.
Decalre the rest, as normal classes(They will have package access). Code:
public class Driver I would suggest you to have the classes in separate files and have them all included in a package |
What Mr. Madhav has created is I think is an inner class rather. It has its own usage
|
Fredstar -
Java deliberately only lets you put one public class in a source file - and the name of the source file has to be the name of the public class. This might not necessarily seem like a good idea if you're working with small, "toy" programs - but it makes a LOT of sense once you're in a production environment with an application that has thousands of classes. If you don't qualify access (i.e. if you don't say "public class" or "private class"), then the class has "package scope": any other class in the same source file, or in the same package, can see it. The only restriction is one (and only one) PUBLIC class per source file - you can have has many "private" or "default scope" classes as you want. |
All times are GMT -5. The time now is 03:40 PM. |