我想知道如何使用另一个包中的类
这是包 project1 中的一个文件
package project1;
class student{
void print(){
System.out.println("s");
}
}
class teacher{
void print(){
System.out.println("t");
}
}
public class Project1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
这是包项目2中的一个文件
package project2;
import project1.student;
public class Project2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
student x = new student();
}
}
但是我得到一个错误,学生不在公共(public)场合,
我是否以错误的方式导入了 student class,以至于我无法使用 student class ,或者不可能这样做?
最佳答案
检查 this link
如果一个类没有修饰符(public
, private
...)它使用默认修饰符,这意味着该类只能从同一个包。
在此this table你会很容易地看到:
访问级别
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N // this is your class
private Y N N N
所以您需要在单独的文件中将Student
类声明为public,或者将Project2
与Student放在同一个包中
和 老师
public class student{
void print(){
System.out.println("s");
}
}
关于java - 如何在java中使用另一个包中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31287689/