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.
-
3The question embodies a contradiction in terms. If the private members are supposed to be accessible, they shouldn't be private. If they're supposed to be private, any technique that exposes them is inherently unsafe and shouldn't be permitted, *in general,* in production code. You should turn the question around and ask whether this is the sort of issue that commonly arises in the interviewer's environment, and why. – user207421 Jun 16 '14 at 09:43
28 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.

- 25,678
- 5
- 79
- 77
Reflection? Omitting imports, this should work:
public class A {
private int ii = 23;
}
public class B extends A {
private void readPrivateSuperClassField() throws Exception {
Class<?> clazz = getClass().getSuperclass();
Field field = clazz.getDeclaredField("ii");
field.setAccessible(true);
System.out.println(field.getInt(this));
}
public static void main(String[] args) throws Exception {
new B().readPrivateSuperClassField();
}
}
It'll not work if you do something like that before the of invocation readPrivateSuperClassField();
:
System.setSecurityManager(new SecurityManager() {
@Override
public void checkMemberAccess(Class<?> clazz, int which) {
if (clazz.equals(A.class)) {
throw new SecurityException();
} else {
super.checkMemberAccess(clazz, which);
}
}
});
And there are other conditions under which the Reflection approach won't work. See the API docs for SecurityManager and AccessibleObject for more info. Thanks to CPerkins for pointing that out.
I hope they were just testing your knowledge, not looking for a real application of this stuff ;-) Although I think an ugly hack like this above can be legit in certain edge cases.

- 4,122
- 4
- 29
- 37
-
1
-
What happens if you don't know, or (for some reason) can't get the name of the field (in this case, `ii`)? Is there some workaround? – YoTengoUnLCD May 27 '16 at 17:34
The architecture is broken. Private members are private because you do not want them accessed outside the class and friends.
You can use friend hacks, accessors, promote the member, or #define private public
(heh). But these are all short term solutions - you will probably have to revisit the broken architecture at some stage.

- 23,168
- 8
- 60
- 63
-
3What do you mean, "the architecture is broken". He's asking about an interview question that will test his Java knowledge, not about designing a real system. – Robert Petermeier Feb 13 '10 at 20:44
-
1By the way if you tell them their code is broken in the interview, it could either help or hinder your chances of getting the job. If it helps, it might be a job you will enjoy. Otherwise, you should keep your CV up-to-date. – Matt Curtis Feb 13 '10 at 20:53
-
1@Robert The architecture is broken because you use private because it's the right thing to do. If that changes, it is a symptom that your design needs changing. "Fixing" it by promoting private to protected is like just telling a just few people your ATM PIN - it will probably be OK in the very short term, but you should change it, or get a joint account or something. – Matt Curtis Feb 13 '10 at 20:57
-
1
-
-
Not necessarily. Things like Hibernate and Spring sometimes need to access private fields. You don't want to make those fields public. This is a valid interview question, and one that I'll ask anybody who walks in claiming to know everything. – Reverend Gonzo Feb 14 '10 at 15:50
-
+1 because my first thought was "check that your class hierarchy is necessary and not broken" because this type of requirement raises a red flag to me. – Greg Beech Feb 14 '10 at 15:55
-
@Reverend If you sometimes need to access private fields, why are they private? (Genuine question, I am not familiar with Hibernate or Spring). – Matt Curtis Feb 14 '10 at 23:05
-
By the way I upvoted @Lachlan's answer because, for newbies, it's the safest answer for an interview. However I would also point out that it is a fairly serious design smell and not one you'd want to just patch over beyond the short term. – Matt Curtis Feb 14 '10 at 23:27
-
@Matt. One example: Hibernate is an ORM (Object relational mapping). What it does is loads your object from some data source (ie: a database) where you define the mapping from fields to columns. This saves you the trouble of having to write SQL yourself. In some cases you can use JavaBean getters/setters but you may not want to expose that information. Specifically, your architecture may not need access to those inner variables, but if you need to serialize that object to data in a way that can be reloaded (and does not use Java Serialization), it may be necessary to access those values. – Reverend Gonzo Feb 15 '10 at 21:17
-
@Matt: On the same note, I will agree that people in general shouldn't be using reflection. There are definite reasons where it should be used and there is no other real option, but this should be left to people who know what they're doing. On the same note, the only time, I've asked that in an interview was when some guy walked in acting like he knew everything under the sun and he had no idea what he was talking about in general. – Reverend Gonzo Feb 15 '10 at 21:26
-
@Reverend Thanks for that example, it's a good one. In cases like this I do concede that it's appropriate to access private members. I agree entirely with your sentiments in your follow-up comment though; there are a lot of devs who don't think through what they're doing and end up with the data flow equivalent of spaghetti code :-) – Matt Curtis Feb 15 '10 at 21:40
By using public accessors (getters & setters) of A's privates members ...

- 2,001
- 3
- 18
- 19
-
You are 100% correct. But tell me one thing : if B doesn't inherit the any private fields of A, where those fields are being stored since we can set them using the setters ? Perhaps a silly question, but it's really confusing me ! – blackSmith Apr 27 '16 at 09:41
You cannot access private members from the parent class. You have make it protected or have protected/public method that has access to them.
EDIT : It is true you can use reflection. But that is not usual and not good idea to break encapsulation.

- 39,895
- 28
- 133
- 186
A nested class can access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
public class SuperClass
{
private int a = 10;
public void makeInner()
{
SubClass in = new SubClass();
in.inner();
}
class SubClass
{
public void inner()
{
System.out.println("Super a is " + a);
}
}
public static void main(String[] args)
{
SuperClass.SubClass s = new SuperClass().new SubClass();
s.inner();
}
}

- 640
- 6
- 22

- 406
- 3
- 6
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.

- 1,772
- 1
- 14
- 24
From JLS §8.3. Field Declarations:
A private field of a superclass might be accessible to a subclass - for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass.
I write the example code:
public class Outer
{
class InnerA
{
private String text;
}
class InnerB extends InnerA
{
public void setText(String text)
{
InnerA innerA = this;
innerA.text = text;
}
public String getText()
{
return ((InnerA) this).text;
}
}
public static void main(String[] args)
{
final InnerB innerB = new Outer().new InnerB();
innerB.setText("hello world");
System.out.println(innerB.getText());
}
}
The explanation of the accessibility of InnerA.text
is here JLS §6.6.1. Determining Accessibility:
Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

- 640
- 6
- 22
You can use the setters and getters of class A. Which gives same feeling as if You are using a class A's object.

- 25,776
- 50
- 140
- 201
Have you thought about making them protected ? Just to be sure you are aware of this option, if you are then pardon me for bringing up this trivia ;)

- 18,317
- 9
- 53
- 64
- 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());
}
}

- 13,303
- 18
- 49
- 71

- 33
- 6
A private member is accessible in subclass in a way that you cannot change the variable, but you are able to access the variable as read only.

- 755
- 3
- 11
- 28
Obviously, making them protected, or adding setters/getters is the preferred technique. Reflection is a desperation option.
Just to show off to the interviewer, IF "access" means read access, and IF Class A generates XML or JSON etc., you could serialize A and parse the interesting fields.

- 15,364
- 7
- 35
- 66
Class A
{
private int i;
int getValue()
{
return i;
}
}
class B extends A
{
void getvalue2()
{
A a1= new A();
sop(a1.getValue());
}
}

- 109
- 1
- 2
To access private variables of parent class in subclass you can use protected or add getters and setters to private variables in parent class..

- 11
- 2
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??

- 194
- 1
- 3
You can't access directly any private variables of a class from outside directly.
You can access private member's using getter and setter.

- 350
- 3
- 13
Ways to access the superclass private members in subclass :
- If you want package access just change the private fields to protected. It allows access to same package subclass.
- If you have private fields then just provide some Accessor Methods(getters) and you can access them in your subclass.
You can also use inner class e.g
public class PrivateInnerClassAccess { private int value=20; class InnerClass { public void accessPrivateFields() { System.out.println("Value of private field : " + value); } } public static void main(String arr[]) { PrivateInnerClassAccess access = new PrivateInnerClassAccess(); PrivateInnerClassAccess.InnerClass innerClass = access.new InnerClass(); innerClass.accessPrivateFields(); } }
4 .You can also use Reflection e.g
public class A { private int value; public A(int value) { this.value = value; } } public class B { public void accessPrivateA()throws Exception { A a = new A(10); Field privateFields = A.class.getDeclaredField("value"); privateFields.setAccessible(true); Integer value = (Integer)privateFields.get(a); System.out.println("Value of private field is :"+value); } public static void main(String arr[]) throws Exception { B b = new B(); b.accessPrivateA(); } }

- 8,806
- 4
- 29
- 34
I don't know about Java, but in some languages nested types can do this:
class A {
private string someField;
class B : A {
void Foo() {
someField = "abc";
}
}
}
Otherwise, use an accessor method or a protected
field (although they are often abused).

- 1,026,079
- 266
- 2,566
- 2,900
By using setter method you can use else with the help of refection you can use private member of class by setting that member say a - take a from class and set a.setAccessible(true);

- 29
- 2
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<String> propertySet = new HashSet<String>();
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 :)

- 2,068
- 4
- 21
- 24
Below is the example for accessing the private members of superclass in the object of subclass.
I am using constructors to do the same.
Below is the superclass Fruit
public class Fruit {
private String type;
public Fruit() {
}
public Fruit(String type) {
super();
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Below is subclass Guava which is inheriting from Fruit
public class Guava extends Fruit{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Guava(String name,String type) {
super(type);
this.name=name;
}
}
Below is the main function where we are creating an object of subclass and also displaying the member of superclass.
public class Main {
public static void main(String[] args) {
Guava G1=new Guava("kanpuria", "red");
System.out.println(G1.getName()+" "+G1.getType());
}
}

- 2,931
- 8
- 29
- 34
Note that a private field of a superclass might be accessible to a subclass (for example,if both classes are memebers of the same class),Nevertheless,a private field is never inherited by a subclass
-
1Private field of a superclass can't be access (directly) by subclass. – alexsmail Sep 25 '12 at 07:06
-
Protected fields on the other hand can be accessed directly by the subclass. – Nate-Wilkins Oct 02 '12 at 14:08
Simple!!!
public class A{
private String a;
private String b;
//getter and setter are here
}
public class B extends A{
public B(String a, String b){ //constructor
super(a,b)//from here you got access with private variable of class A
}
}
thanks

- 266
- 5
- 13
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
}
}

- 472
- 4
- 12
-
This is not an answer to the question. There is no subclass in your example. – Bevor Jun 13 '22 at 07:57
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

- 2,687
- 5
- 37
- 59