JAVA 中 protected 的一些个人理解

首先需要对 protected 进行溯源:

例如

	class A {
		protected  void  fun(){
		}
	}

	class B extends A {
		
	}
	
	class main_l {
		public static void main(String[] args) {
			A  a = new A();
			B  b = new B();
			a.fun();
			b.fun();
		}
	}
a.fun()和b.fun()的源头都是在 class A 当中;
//====================================================
	class A {
		protected  void  fun(){
		}
	}

	class B extends A {
		protected  void  fun(){
		}
		
	}
	
	class main_l {
		public static void main(String[] args) {
			A  a = new A();
			B  b = new B();
			a.fun();
			b.fun();
		}
	}
a.fun()的源头是在 A中  b.fun()的源头是在 class B中。
==========================================================
多重继承下
class A {
		protected  void  fun(){
		}
	}

	class B extends A {
		protected  void  fun(){
		}
		
	}
	class C extends B {

		
	}
	class D extends C {
		protected  void  fun(){
		}
	}
	
	class main_l {
		public static void main(String[] args) {
			A  a = new A();
			B  b = new B();
			C  b = new C();
			D  b = new D();
			
			a.fun();
			b.fun();
			c.fun();
			d.fun();
		}
	}
a.fun()的源头是在 A中 b.fun()的源头是在 class B中 c.fun()的源头是在 class B中
d.fun()的源头是在 class D中;
==============================================================

对于基类以及子类的变量或者是方法当中,清楚了溯源之后;需要知道第二点。

1、**若子类与基类在同一包中,基类的 protected 成员是包内可见的,并且对子类可见;(这句话很重要!!!)**

2、若子类与基类不在同一包中,那么在子类中,子类实例可以访问其从基类继承而来的protected方法,而**不能**访问基类实例的protected方法;
	若基类子类不在一包中   基类的protected成员 子类无法对其访问
	
	
一些例程 可以再看一下如下链接
https://www.runoob.com/w3cnote/java-protected-keyword-detailed-explanation.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ah_yl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值