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

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

    Directly we can't access it. but Using Setter and Getter we can access,

    Code is :

    class AccessPrivate1 {    
    
        private int a=10; //private integer    
        private int b=15;    
        int getValueofA()    
        {    
            return this.a;    
    
        }    
    
        int getValueofB()    
        {    
            return this.b;    
        }    
    }    
    
    
    public class AccessPrivate{    
        public static void main(String args[])    
        {    
            AccessPrivate1 obj=new AccessPrivate1();    
    
            System.out.println(obj.getValueofA()); //getting the value of private integer of class AccessPrivate1    
    
            System.out.println(obj.getValueofB()); //getting the value of private integer of class AccessPrivate1    
        }    
    }    
    

提交回复
热议问题