Java – how do I import my own classes?
•
Java
I have this Java class:
package myClass;
public class myClass
{
private int herAge ;
public void setHerAge (int herAge)
{
this.herAge = herAge ;
}
}
I want to exist in the same directory named test After compiling it in another source file of Java, import this class, here test Java includes:
import myClass ;
public class Test
{
public static void main (String []args)
{
myClass Rudaina = new myClass();
Rudaina.setHerAge(30);
}
}
When I compile test Java, I saw this in my console:
Test.java:1: error '.' expected
import myClass ;
^
Test.java:1: error '.' expected
import myClass ;
^
Solution
Your class MyClass is also in the package named MyClass, which may cause confusion
Try:
import myClass.myClass;
This is called the fully qualified name of the class
Packages are used to group conceptually related classes Having a package named after a single class is not very useful
You can name your package after the project name For example, you can name it
package assignment1;
Then import your class like this:
import assignment1.myClass;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
