java protected关键字的访问权限

   学过java的都知道,protected的访问权限对子类来说,无论在包里还是保外都能访问的,真实情况是什么样的呢?同包下的子类继承就不研究了,主要看下不同包下的子类

    父类:

package com.father;

       public class Father1 {
	
	   String name;
	   public int age;
	   protected String color;

  }

   子类:

package com.son;

import com.father.Father1;

public class Son extends Father1{
	
	public static void main(String[] args) {
		String c;
		// TODO Auto-generated method stub
                Father1 f = new Father1();
                c = f.color;//无法访问,报错

                Father1 f = new Son();
                c = f.color;//无法访问,报错

                Son s = new Son();
                c = s.color;//正常
	}

}

 

  在Son类中新建个副类:

class Son2 extends Son{
	
	public static void main(String[] args) {
		String c;
		Son s = new Son2();
		c = s.color;//无法访问,报错
		
		Son2 s2 = new Son2();
		c = s2.color;//正常
	}

 

 

    由此可以看出只能是子类自己的实例对象才能访问父类protected,其他的都不能访问

    这里再给出《java in a nutshell》中的一段话:

protected access requires a little more elaboration. Suppose class A declares a protected field x and is extended by a class B, which is defined in a different package (this last point is important). Class B inherits the protected field x, and its code can access that field in the current instance of B or in any other instances of B that the code can refer to. This does not mean, however, that the code of class B can start reading the protected fields of arbitrary instances of A! If an object is an instance of A but is not an instance of B, its fields are obviously not inherited by B, and the code of class B cannot read them.

    

     

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值