我遇到了一个任务问题,其中任务只是将包含多个类的单个java文件分解为多个java文件,然后导入这些java文件,以便原始项目仍然有效。(总共4个类,将其中的3个移动到单独的文件中)
我创建了一个新项目并将一个类移动到该新项目。然后将其导入我的原始文件并将必要的功能设置为公共,它可以正常工作。
对于其他两个课程,我必须创建一个名称完全不同的新项目(例如Five
)并将文章Three
和Four
粘贴到此项目中。然后将这两个类导入到原始文件中。
我这样做,它说类Three
和Four
应该是公开的。然而,这是不可能的,因为班级Five
已经公开。如何从原始文件中访问这两个类?
项目一:(这是我试图运行的那个)
package one;
import two.Two;
import five.Five;
public class One {
public static void main(String[] args) {
...
}
)
class Customer{
...//this class accesses attributes and methods of classes
//Two, Three and Four. The error occurs for methods from classes Three and Four
}
第二个项目
package two;
public class Two {
public static void main(String[] args) {
...
}
)
项目五
package five;
public class Five {
public static void main(String[] args) {
...
}
}
class Three{
...
}
class Four{
...
}
答案 0 :(得分:1)
看一下这个问题(和答案):Can a java file have more than one class?
每个文件只能有一个公共类。如果您不希望Three
和Four
作为Five
中的内部静态类,则必须将它们放在单独的文件中 Three.java 和 Four的.java
另外,package
可以等同于一个文件夹,所以如果你的类在同一个文件夹中(一个模块/逻辑单元的一部分),它们都可以在同一个包中,比如main
因此,您的包main
将包含Java文件中的所有类(这也是一种好的做法,除非一个类在逻辑上是另一个类的子单元)。另请注意,同一包中的类不需要导入。他们甚至不必公开。
答案 1 :(得分:0)
如上面的答案中一个.java文件只有一个公共类,我们不能让其他类公开,所以其他类不能被不同包的类访问,因为这些类是默认的,只有它们的可见性。 s包。其他包无法访问这些类。
但是,如果你真的想在下面做例子就是这样做的方法之一。
package pack1;
public class A {
public void sum(int a, int b){
System.out.println("Addition of a and b ="+(a+b));}
public static class Sub
{
public void subtraction(int a, int b)
{
System.out.println("subtraction a-b ="+(a-b));
}
}
}
// below main class is written and in that main class we are accessing the above classes of pack1
package mypack;
import pack1.*;
public class B {
public static void main(String[] args) {
A o1=new A();
int a=50,b=20;
o1.sum(a,b);
A.Sub o2=new A.Sub();
o2.subtraction(a,b);
}
}