views:

81

answers:

5

So the way i've been told to do things is you have your file and the file name is Classname.java and then the code is something like this:

class ClassName { 
SOME METHODS 
main {} 
}

and then thats all.

I'd like to have two objects defined and used within the same .java file. (i don't want to have to put the other class in a difernt file just because i'd like to send this to someone and i want to avoid hasstle of atatching multiple files to an email [the lazy do make good programers though if you think about it])

  • is it possible to do this?
  • do i have to do anything special and if so what?
  • what are some mistakes i'm likely to make or that you have made in the past when doing this?
+2  A: 

First of all there is a difference in Objects and Classes. You can't just use those interchangeably.

Now, yes you can define multiple classes in a single file. But the name of the file should reflect the name of a public class in there, other classes should not be public.

Adeel Ansari
A: 
  • Yes you can do this, though the named once must be public.
  • No, nothing special has to be done.
Mimisbrunnr
+3  A: 

Yes, you can have two classes defined in the same file. You need to define one of them as public, and that same class has to match the name of the file. Example:

file name = Foo.java

public class Foo { 

}

class Bar { 

}
Amir Afghani
I believe the subclass must be nested within the public.
Kavon Farvardin
@Kavon: Where is the subclass?
Adeel Ansari
@Adeel, nevermind I thought the OP was asking about subclasses.
Kavon Farvardin
+1  A: 

You can put multiple classes in the same .java file. You can't put multiple public classes in the same .java file.

You can put the main class (public), followed by the other classes with default access, in the same .java file.

Nicolás
A: 

The only way to specify multiple classes in a single java file is to use inner classes.

So for Foo.java

you would have:

public class Foo {

main {}

public class bar { .... }

public class qux { .... }

}

You may read more of this here: http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html

NeXus 5ix
Inner classes cannot be declared public.
Anthony Forloney
@Anthony unless they are static
tony