java中包的子类,java – 超类中的受保护方法在不同包中的子类中是否可见?

package com.one;

public class SuperClass {

protected void fun() {

System.out.println("base fun");

}

}

----

package com.two;

import com.one.SuperClass;

public class SubClass extends SuperClass{

public void foo() {

SuperClass s = new SuperClass();

s.fun(); // Error Msg: Change visibility of fun() to public

}

}

我也从oracle doc和here中读到,受保护的成员也可以在另一个包的子类中看到.所以fun()应该在包2中的SubClass中可见.那为什么错误?

我非常想念一些非常明显的东西吗?

解决方法:

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

这意味着如果你在原始类的包之外编写一个子类,每个对象都可以调用超类的受保护方法,而不是其他对象.

在您的示例中,因为s是与此不同的对象,所以不能调用s.fun().但是该对象可以通过this.fun()或fun()调用自己的有趣方法.

标签:superclass,java,inheritance,access-modifiers,protected

来源: https://codeday.me/bug/20190929/1832980.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值