开发者

In java can i have more than one class/object in a file?

开发者 https://www.devze.com 2022-12-22 18:30 出处:网络
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:

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?


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 { 

}


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.


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.


  • Yes you can do this, though the named once must be public.
  • No, nothing special has to be done.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消