通过继承访问内部类的受保护字段

时间:2016-06-15 13:10:44

标签: java inheritance inner-classes

我正在尝试通过访问Inner类的受保护字段 继承在另一个内部类中。但我遇到了一个问题:

  package a;

    class A{

        public class Inner{
           protected int i =5;
        }
    }

    package b;
    class B{

        public class BInner extends A.Inner{
         dsds
          void test(){
               System.out.println(i);  // that's works fine, i 
            }
        }

       void print(){
         System.out.println(new BInner().i)  // but why i cant access this field from here?  Compiler just says that there is protected access ... 
         }
    }

是否有办法访问此字段?

1 个答案:

答案 0 :(得分:-1)

protected访问修饰符表示该字段或方法仅对类本身及其子项可用。由于课程B未展开B.BInner,因此无法访问B.BInner.i

使用访问修饰符的最常用方法是使用 getter / setter pair ,您可以在A.Inner中声明(因为那里i声明,B.BInner将继承方法):

class A{

    public class Inner{
       protected int i =5;

       public int getI() {
           return i;
       }

       public void setI(int i) {
           this.i = i;
       }
    }
}

getI()对象上调用B.BInner将返回i的值,并且因为它public,它可以在任何地方使用。