File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes inheritance and private instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "inheritance and private instance variables" Watch "inheritance and private instance variables" New topic

inheritance and private instance variables

Scott Updike
Ranch Hand

Joined: Feb 16, 2006
Posts: 92
If private class members (instance variables and methods for example) are not inherited, then if I have a class who's superclass has public getter and setter methods with a private instance variable, then how does the subclass call a setter method on an instance variable that it does not inherit?


public class A {
private String name;

public void setName (String name) { = name;


public class B extends A {

private String name2;

public void setName2(String name) {
this.name2 = name;


Now, when I say

String myName = "Blah";
B b = new B();

How does that work if name (from class A) is not extended to B since it's private but the setter is public? I must be missing something....

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
Well the subclass is aware of the private member of the superclass, but it can't access it directly. But the public getter methods from the superclass allow it to interact with its private members.
I agree. Here's the link:
subject: inheritance and private instance variables
It's not a secret anymore!