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

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

    • Private members cant be accessed in derived class
    • If you want to access means you can use getter and setter methods.
    class A
    {
     private int a;
     void setA(int a)
     {
        this.a=a;
     }
     int getA()
     {
       return a;
     }
    }
    
    Class B extends A
    {
     public static void main(String[] arg)
      {
         B obj= new B();
         obj.setA(10);
         System.out.println("The value of A is:"+obj.getA());
      } 
    }
    

提交回复
热议问题