I am trying to test the following situation:
- There is a main. (
city.Main
) - There is a package. (
package castle
) - Within the package, there is a public class (
castle.Guard
), and a package-private class (castle.Princess
). - What if, the public class is returning an instance of the private class?
Here is my code:
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"); }
}
Notice all the 4 statements in main()
are having errors.
I have done some research too. In fact i want to mimic this answer. But i don't why my codes throw errors.
Thanks for any explanations!
Edit:
I intend to make the castle-Princess
package-private. I know that, by returning a package-private class out of its package, I should be prepared for errors. But why that answer works, while mine doesn't?