java中的protected访问符深入理解

说到protected访问符,我首先想到的是包内和子类(或者子类的子类)可以访问。

但是其中却有值得我注意的:

我先在test01包中定义Father类:

package test01;

public class Father {
	protected void s() {
		System.out.println("可以调用");
	}
}

然后在test02包中定义SonA类并且继承Father

package test02;

import test01.Father;

public class SonA extends Father{
	public static void main(String[] args) {
//		Father father = new Father();
//		father.s();    //这里会报错The method s() from the type Father is not visible
		SonA sA = new SonA();
		sA.s();//子类继承了父类,当然可以访问继承过来的protected方法,不报错
	}
}

在test02包中定义SonB类并且继承Father

package test02;
import test01.Father;
public class SonB extends Father{
	public static void main(String[] args) {
		SonA sA = new SonA();
		sA.s(); // 这里会报错,The method s() from the type Father is not visible
	}
}
总结:总之就是只能自己用自己继承过来的protected方法,不能在自己方法中调用兄弟子类继承的protected也不能调用父类的protected方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值