我正在尝试测试以下情况:
city.Main
)package castle
)castle.Guard
)和一个包私有类(castle.Princess
)。 这是我的代码:
Main.java
package city;
import castle.Guard;
public class Main {
public static void main(String[] args) {
Princess princess = Guard.getPrincessStatic();
// Error: Princess cannot be resolved to a type
Guard.getPrincessStatic().sayHi();
// Error: The type Princess is not visible
Guard guard = new Guard();
guard.getPrincess().sayHi();
// Error: The type Princess is not visible
guard.getPrincessMember().sayHi();
// Error: The type Princess is not visible
}
}
Guard.java
package castle;
public class Guard {
public Princess getPrincess() {
return new Princess();
}
public static Princess getPrincessStatic() {
return new Princess();
}
private Princess m_princess = new Princess();
public Princess getPrincessMember() {
return m_princess;
}
}
Princess.java
package castle;
class Princess {
public void sayHi() { System.out.println("Hi world"); }
}
注意
main()
中的所有4条语句都有错误。我也做了一些研究。实际上,我想模仿this answer。但是我不为什么我的代码会引发错误。
感谢您的解释!
编辑:
我打算将
castle-Princess
打包为私有。我知道从包中返回包私有类,我应该为错误做好准备。但是,为什么that answer有效,而我的无效? 最佳答案
Princess
类的默认范围是castle
包,因此它在city
包中不可见。为了规避这一点:
(我们可以执行以下三种方法之一。)
1)制作Princess
类public
并使用它。
package castle;
// added public modifier
public class Princess {
public void sayHi() { System.out.println("Hi world"); }
}
2)或者,定义一个
public interface
并让Princess
实现它,并使用interface reference
代替class reference
。我更喜欢这个。城堡\ IPrincess.java
// Interface definition
package castle;
public interface IPrincess {
public void sayHi();
}
城堡\ Princess.java
// Implement the interface in Princess class
package castle;
class Princess implements IPrincess {
public void sayHi() { System.out.println("Hi world"); }
}
城堡\ Guard.java
// Modify the Guard class
package castle;
public class Guard {
public IPrincess getPrincess() {
return new Princess();
}
public static IPrincess getPrincessStatic() {
return new Princess();
}
// for here i use Princess instead of IPrincess. (@midnite)
private Princess m_princess = new Princess();
public IPrincess getPrincessMember() {
return m_princess;
}
}
市\ Main.java
// Modify the main class
package city;
import castle.Guard;
import castle.IPrincess;
public class Main {
public static void main(String[] args) {
IPrincess princess = Guard.getPrincessStatic();
Guard.getPrincessStatic().sayHi();
Guard guard = new Guard();
guard.getPrincess().sayHi();
guard.getPrincessMember().sayHi();
}
}
3)或者,将所有类放在同一包中。