How to access the private variables of a class in its subclass?

前端 未结 28 2308
清歌不尽
清歌不尽 2020-12-17 09:46

This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the qu

28条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 10:33

    Ways to access the superclass private members in subclass :

    1. If you want package access just change the private fields to protected. It allows access to same package subclass.
    2. If you have private fields then just provide some Accessor Methods(getters) and you can access them in your subclass.
    3. You can also use inner class e.g

      public class PrivateInnerClassAccess {
      private int value=20;
      
      class InnerClass {
      
      public void accessPrivateFields() {
          System.out.println("Value of private field : " + value);
      }
      
      }
      
      public static void main(String arr[])
      {
          PrivateInnerClassAccess access = new PrivateInnerClassAccess();
          PrivateInnerClassAccess.InnerClass innerClass = access.new InnerClass();
          innerClass.accessPrivateFields();
      
      }
      
      }
      

      4 .You can also use Reflection e.g

       public class A {
      private int value;
      public A(int value)
      {
          this.value = value;
      }
      }
      
      public class B {
      public void accessPrivateA()throws Exception
      {
          A a = new A(10);
          Field privateFields = A.class.getDeclaredField("value");
          privateFields.setAccessible(true);
          Integer value = (Integer)privateFields.get(a);
          System.out.println("Value of private field is :"+value);
      }
      
      
      public static void main(String arr[]) throws Exception
      {
          B b = new B();
          b.accessPrivateA();
      }
      }
      

提交回复
热议问题