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

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

    If I'm understanding the question correctly, you could change private to protected. Protected variables are accessible to subclasses but behave like private variables otherwise.

    0 讨论(0)
  • 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    
        }    
    }    
    
    0 讨论(0)
  • 2020-12-17 10:36

    Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:

    • Java Access Modifiers
    • Non Access Modifiers

    To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement.

    There is more information here:

    http://tutorialcorejava.blogspot.in/p/java-modifier-types.html

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

    You can't access directly any private variables of a class from outside directly.

    You can access private member's using getter and setter.

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

    You can use Accessors (getter and setter method) in your Code.

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

    Private will be hidden until you have been given the right access to it. For instance Getters or setters by the programmer who wrote the Parent. If they are not visible by that either then accept the fact that they are just private and not accessible to you. Why exactly you want to do that??

    0 讨论(0)
提交回复
热议问题