Java 如何导入我自己的类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28651061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import my own class?
提问by mahmoud nezar sarhan
I have this java class :
我有这个java类:
package myClass;
public class myClass
{
private int herAge ;
public void setHerAge (int herAge)
{
this.herAge = herAge ;
}
}
and I want to import this class after compile it in another source file called Test.java exists in the same directory , and here what Test.java contains :
我想在将这个类编译到另一个名为 Test.java 的源文件中后导入它,该文件存在于同一目录中,这里 Test.java 包含:
import myClass ;
public class Test
{
public static void main (String []args)
{
myClass Rudaina = new myClass();
Rudaina.setHerAge(30);
}
}
when I compile Test.java I see this in my console :
当我编译 Test.java 时,我在控制台中看到了这个:
Test.java:1: error '.' expected
import myClass ;
^
Test.java:1: error '.' expected
import myClass ;
^
采纳答案by iFytil
Your class myClass
is also in package called myClass
, which can be a cause of confusion.
您的课程myClass
也在名为 的包中myClass
,这可能会引起混淆。
Try:
尝试:
import myClass.myClass;
This is called the fully qualified name of the class.
这称为类的完全限定名称。
A package is meant to group classes which are conceptually related. Having a package named after a single class is not very useful.
包旨在对概念上相关的类进行分组。以单个类命名的包不是很有用。
You could name your package after the name of your project. For instance, you could name it
你可以用你的项目名称来命名你的包。例如,您可以将其命名为
package assignment1;
And then import your class like this:
然后像这样导入你的类:
import assignment1.myClass;
回答by Maksim
You should use the whole class name - including the name of the package.
您应该使用整个类名 - 包括包的名称。
回答by Jared Mackey
You are missing the package name. Try import myClass.myClass;
您缺少软件包名称。尝试import myClass.myClass;
回答by Ellen Spertus
While what everyone wrote is true, since the two files are in the same directory, no import should be necessary.
虽然大家写的都是对的,但是因为这两个文件在同一个目录下,所以不需要导入。
FYI, it is customary to capitalize the names of classes.
仅供参考,习惯上将类的名称大写。