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

前端 未结 28 2305
清歌不尽
清歌不尽 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 propertySet = new HashSet();
        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 :)

提交回复
热议问题