Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

core

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 question is: I need to access private members of class A from class B, rather than create variables with the same value in class B.

like image 920
giri Avatar asked Feb 13 '10 20:02

giri


People also ask

Can you access private variables from subclass?

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

How do you access a private variable in a superclass in a subclass?

To access the private members of the superclass you need to use setter and getter methods and call them using the subclass object.

Can you access private variables within a class?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class. Example: using System; using System.

How do you access private members of a class?

2. Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of the class.


1 Answers

The interviewer was either testing your knowledge of access modifiers, or your approach to changing existing classes, or both.

I would have listed them (public, private, protected, package private) with an explanation of each. Then gone on to say that class A would need to be modified to allow access to those members from class B, either by adding setters and getters, or by changing the access modifiers of the members. Or class B could use reflection. Finally, talk about the pros and cons of each approach.

like image 172
Lachlan Roche Avatar answered Oct 05 '22 08:10

Lachlan Roche