java同包可以访问修饰_Java中的受保护和包私有访问修饰符之间的区别?

我已经看到有关保护和包私有修饰符之间差异的各种文章。有一件事我发现这两个职位矛盾

在这个接受的答案中说

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

在这个接受的答案中说

To satisfy protected level access two conditions must be met:

The classes must be in the same package.

There must be an inheritance relationship.

不是矛盾吗?从我对其他文章的理解,第一篇文章给出了正确的答案,在其他包中protected == package-private子类。

如果这个语句是正确的,那么为什么这个代码在第17行的子类Cat上失败,出现以下错误消息

The method testInstanceMethod() from the type Animal is not visible

我的超级和子类代码如下。

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.");

}

public void testInstanceMethod() {

System.out.println("The instance method" + " in Cat.");

}

public static void main(String[] args) {

Cat myCat = new Cat();

Animal myAnimal = myCat;

myAnimal.testClassMethod();

myAnimal.testInstanceMethod();

}

}

请澄清为什么上述代码失败。这将是非常有用的。谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值