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

前端 未结 28 2202
清歌不尽
清歌不尽 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:31

    You may want to change it to protected. Kindly refer this

    https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    If this is something you have to do at any cost just for the heck of doing it you can use reflection. It will give you list of all the variables defined in the class- be it public, private or protected. This surely has its overhead but yes, it is something which will let you use private variables. With this, you can use it in any of the class. It does not have to be only a subclass Please refer to the example below. This may have some compilation issues but you can get the basic idea and it works

    private void getPropertiesFromPrivateClass(){
    
        Field[] privateVariablesArray = PrivateClassName.getClass().getDeclaredFields();
        Set<String> propertySet = new HashSet<String>();
        Object propertyValue;
        if(privateVariablesArray.length >0){
            for(Field propertyVariable :privateVariablesArray){
                try {
    
                    if (propertyVariable.getType() == String.class){
                        propertyVariable.setAccessible(true);
                        propertyValue = propertyVariable.get(envtHelper);
                        System.out.println("propertyValue");
                    }
                } catch (IllegalArgumentException illegalArgumentException) {
                    illegalArgumentException.printStackTrace();
    
                } catch (IllegalAccessException illegalAccessException) {
                    illegalAccessException.printStackTrace();
    
                }
            }
    

    Hope this be of some help. Happy Learning :)

    0 讨论(0)
  • 2020-12-17 10:32
        Class A
    {
      private int i;
    
      int getValue()
        {
          return i;
      }
    }
    class B extends A
    {
       void getvalue2()
        {
          A a1= new A();
          sop(a1.getValue());
        }
    }
    
    0 讨论(0)
  • 2020-12-17 10:32

    Note that a private field of a superclass might be accessible to a subclass (for example,if both classes are memebers of the same class),Nevertheless,a private field is never inherited by a subclass

    0 讨论(0)
  • 2020-12-17 10:33

    By using setters and getters u can access it

    0 讨论(0)
  • 2020-12-17 10:33

    I don't know about Java, but in some languages nested types can do this:

        class A {
            private string someField;
            class B : A {
                void Foo() {
                    someField = "abc";
                }
            }
        }
    

    Otherwise, use an accessor method or a protected field (although they are often abused).

    0 讨论(0)
  • 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();
      }
      }
      
    0 讨论(0)
提交回复
热议问题