在Java中,文件中可以有多个类/对象吗? [英] In java can i have more than one class/object in a file?

查看:77
本文介绍了在Java中,文件中可以有多个类/对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以有人告诉我做事的方式是您有文件,文件名是 Classname.java ,然后代码是这样的:

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 {} 
}

然后就是这些。

我想在同一个 .java 文件中定义和使用两个对象。 (我不想仅仅将另一个类放在一个不同的文件中,只是因为我想将其发送给某人,并且我想避免将多个文件附加到电子邮件中的麻烦[懒惰的人会成为优秀的程序员,尽管您考虑一下))

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])


  • 是否可以这样做?

  • 我必须做些特别的事情吗?

  • 这样做时,我可能会犯什么错误,或者您过去犯过什么错误?

推荐答案

是的,您可以在同一文件中定义两个类。您需要将其中之一定义为public,并且同一类必须与文件名匹配。示例:

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 { 

}

这篇关于在Java中,文件中可以有多个类/对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆