JAVA中修饰符protected

1. 类成员的访问控制修饰符protected表示该类所属包内的类或该类的派生类可以访问protected成员。

1.2 针对protected成员,有一个容易误解的地方,请看下面的代码

<pre name="code" class="java">//Base.java
package test;

public class Base {
	  protected int i=0;
}

//TestProtected.java
import test.Base;

public class TestProtected extends Base {
    public static void main(String [] args) {
          TestProtected tp = new TestProtected();       
          System.out.println(tp.i); //Correct , 派生类中继承了基类的protected成员,派生类中能访问派生类对象所继承的protected成员       
          Base bbb = new Base();
          System.out.println(bbb.i); //Error , 不能访问基类对象的protected成员       
    }
}
 

1.3 通过以上代码,可以得出结论:在生成派生类时,派生类可以继承基类的protected成员,这个继承的protected成员在派生类内部是可以访问的,但是在派生类内部无法直接访问基类对象的protected成员。

1.4 更进一步,一种派生类内部只能访问该种派生类的对象继承的基类protected成员,不能访问基类的其他派生类对象继承的基类protected成员。请看代码:

//Base.java
package test;
public class Base {
      otected int i=0;
} 
//TestProtected.java
import test.Base; 
public class TestProtected  extends Base {
      public static void main(String [] args) {
            TestProtected tp1 = new TestProtected();
            derive tp2 = new Derive();        
            System.out.println(tp1.i); // correct
            System.out.println(tp2.i); //Compile error       
      }
} 
class Derive extends Base {
}



2.虽然protected域对所有子类都可见。但是有一点很重要,子类只能在自己的作用范围内访问自己继承的那个父类protected域,而无法到访问别的子类(同父类的亲兄弟)所继承的protected域。  总之,当B extends A的时候,在子类B的作用范围内,只能调用本子类B定义的对象的protected方法(该方法从父类A中继承而来)。而不能调用其他A类对象的protected 方法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值