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

馋奶兔 提交于 2020-01-03 02:24:06

问题


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?

回答1:


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 { 

}



回答2:


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.




回答3:


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.




回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/2445007/in-java-can-i-have-more-than-one-class-object-in-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!