简体   繁体   English

在Java中,文件中可以有多个类/对象吗?

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

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: 因此,有人告诉我做事的方式是您有文件,文件名是Classname.java ,然后代码是这样的:

class ClassName { 
SOME METHODS 
main {} 
}

and then thats all. 然后就这样。

I'd like to have two objects defined and used within the same .java file. 我想在同一个.java文件中定义和使用两个对象。 (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. 您需要将其中之一定义为public,并且同一类必须与文件名匹配。 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. 但是文件名应该反映那里的public类的名称,其他类则不应是公共的。

You can put multiple classes in the same .java file. 您可以将多个类放在同一个.java文件中。 You can't put multiple public classes in the same .java file. 您不能将多个公共类放在同一个.java文件中。

You can put the main class ( public ), followed by the other classes with default access, in the same .java file. 您可以将主类( public )和其他具有默认访问权限的类放在同一.java文件中。

  • 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. 在单个java文件中指定多个类的唯一方法是使用内部类。

So for Foo.java 因此对于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 您可以在这里阅读更多内容: http : //java.sun.com/docs/books/tutorial/java/javaOO/nested.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM