4

I've read in a textbook that class members that are marked as private are not inherited. So I thought if class A has a private variable x and class B would extend class A then there would be no variable x in class B. However a following example shows that I misunderstood that:

public class testdrive
{
    public static void main(String[] args) {
        B b = new B();
        b.setLength(32);
        System.out.print(b.getLength());
    }
}

class A {
    private int length;
    public void setLength(int len) {
        length = len;
    }
    public int getLength() {
        return length;
    }
}

class B extends A {
    public void dummy() {
    }
}

The result is 32 and I'm confused because it looks like object with ref b now has the variable length and it's value is 32. But ref b refers to object created from class B where the length variable is not defined. So what's the truth, does class B inherit the private variable length? If so, what does it mean that private variables are not inherited?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
griboedov
  • 876
  • 3
  • 16
  • 33

3 Answers3

3

The field that is private is hidden in B. But, your public methods are inherited and are accessible, and they can access the private field.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Hey man it's not how you think it is, private fields can only be accessed by the methods present in the same class (given ofcourse that the methods are accessible from other class)

its not that you can directly call:

b.length=8;

Or you cannot even do this:(write this where you created the object for B)

A a = new A();
a.length=8;

both of these approach are invalid!

For more info:

you don't even need to extend B from A, just create an object of A in main and use those get and set methods of yours and it will work too!

Sarthak Mittal
  • 5,794
  • 2
  • 24
  • 44
-1

You don't have direct access to the private fields and method of a superclass but you are able to access them through the use of other public methods.

This is one of the fundamental concepts of the Object-Oriented Programming and it's named Encapsulation. Read more about this here : TutorialsPoint.

Bottom-line : You can't directly access a private field or method like this

b.length = 32;

nor like this (for the superclass)

A a = new A();
a.length = 32;

but you can manipulate those fields through the use of a public method like in your example.

The reason is simple : your private fields/methods are hidden for other classes except for the class which holds them , but your public fields/methods are not hidden.

Community
  • 1
  • 1
SCBbestof
  • 34
  • 1
  • 6