在Java中,有没有关于何时使用每个访问修饰符,即默认明确的规则(包私有)public,protected并且private,同时使class与interface和处理继承?
我有两个包
uk.co.planetbeyond.data
Run Code Online (Sandbox Code Playgroud)
和
uk.co.planetbeyond.data.bean
Run Code Online (Sandbox Code Playgroud)
如何使uk.co.planetbeyond.data.bean类在父包中的类中可见,uk.co.planetbeyond.data但在其他包中不可见?
它甚至可能吗?
我已经看过有关protected和package private修饰符之间差异的各种文章.有一件事我发现这两个帖子之间存在矛盾
在这个被接受的答案说
protected修饰符指定只能在其自己的包中访问该成员(与package-private一样),此外,还可以在另一个包中通过其类的子类访问该成员.
在这个被接受的答案说
要满足受保护级别访问,必须满足两个条件:
- 这些类必须在同一个包中.
- 必须有继承关系.
他们不矛盾吗?根据我对其他文章的理解,第一篇文章给出了正确的答案,即在其他包中保护== package-private + subclass.
如果此语句是正确的,那么为什么此代码失败,并在第17行的子类Cat上出现以下错误消息
The method testInstanceMethod() from the type Animal is not visible
Run Code Online (Sandbox Code Playgroud)
我的超级和子类代码如下.
package inheritance;
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
protected void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}
package testpackage;
import inheritance.Animal;
public class Cat extends Animal{
public static void testClassMethod() {
System.out.println("The class method" + " in Cat."); …Run Code Online (Sandbox Code Playgroud) 我一直在与OSGi合作一段时间,但我仍然不了解私有包.
并非所有未导出的捆绑包对所有其他包都不可见吗?如果是这样,那么未导出的私有包和包有什么区别?
我已经阅读了OSGi in Action和"OSGi和Apache Felix 3.0 - 初学者指南",但我无法找到差异.
我看到有两种方法可以在 JAVA 中声明/定义变量:public 和 private。我的问题是,如果定义的变量没有被视为“公共”或“私有”会发生什么,例如:
int num;
Run Code Online (Sandbox Code Playgroud)
'num' 被认为是私人的还是公共的?