Do subclasses inherit private fields?
Asked Answered
E

21

288

This is an interview question.

Does subclasses inherit private fields?

I answered "No", because we can't access them using the "normal OOP way". But the interviewer thinks that they are inherited, because we can access such fields indirectly or using reflection and they still exist in the object.

After I came back, I found the following quote in the javadoc:

Private Members in a Superclass

A subclass does not inherit the private members of its parent class.

Do you know any arguments for the interviewer's opinion?

Egan answered 17/1, 2011 at 17:34 Comment(19)
Sounds like, from your question, a simple "yes" or "no" answer isn't deep enough. I think you've captured the essence of the matter right there, though.Wanderjahr
I was in a similar situation once and I realised I didn't even want to work for a company where the interviewer knows less about Java than me. :)Threesquare
@biziclop, Probably it's same situation) But I want check my answer.Egan
An interviewer will sometimes disagree with you even when he knows you're right. A good interviewer will try to learn more about you than your technical knowledge.Levorotatory
@Andy Thomas-Cramer, It's good point. I don't think about this before.Egan
@DigitalRoss Is the Java Language Specification also badly written? See RD01 answer: #4716540Alkyne
Heh, I knew Bill Joy in Berkeley when he was a grad student. If I ever see him again I'm going to complain about that use of inherit. I guess the word "inherit" has multiple meanings, and it's OK, at least with Java, to use it that way. But it most definitely will cripple your understanding of OOP if you take it literally, and not realize that they are using it to describe an encapsulation inheritance policy and not behavior inheritance.Laynelayney
@Andy Thomas-Cramer I wouldn't want to work with people who are deliberately lying to test my reaction either.Threesquare
In my opinion interviewer was right about saying that they get inherited, but they are not accessible, both are different things. Its the matter how you really understand the concept of inheritance. for the sake of argument i would like to let you remind that whenever you create an object of child class object of parent or super class gets created, you can modify the behaviors by overriding functions or you could add more properties or fields to the child but all fields of parent class would be initiated in memory and you are using those fields as well indirectly by calling parent class funcs.Trumaine
@Trumaine Ahmad, Since JLS defines that it doesn't, any other source is wrong, isn't it?Egan
@Stas Kurlin: You argument is valid, this is what i was saying that it really matters how you understand Inheritance, all these terminologies are open for debate and there is no single definition of OOP concepts, like if you try to find out one definition of Aggregation you will end up having more than 5 or 6 different definitions, same case is with Abstraction, Difference between Function Overloading and Overriding etc.Trumaine
@Stas Kurlin: So I have my own view regarding these concepts, and I look on it according to Object's perspective and being a child object even if it doesn't have direct access to the values of private fields it still uses private fields by one way or another, So try to bring you view out of a particular programming language and then give it a thought. ThanksTrumaine
@Trumaine Ahmad . Let's go out of particular programming language. Can we be sure that object will contain all fields from it parent? No. It could be implemented in very differ way. So why should we ever think that they do inherit it? All our definition is about interfaces (not implementations). Private fields are not accessible, so we don't inherit it.Egan
@Stas Kurilin: In any programming language, any child object initialize the parent object, hence all the fields are inherited, but there might be few of them which can not be altered or read by child object directly such fields would be marked as private.Trumaine
I think the both answers are correct if you don't EXPLICITLY define what you mean by inheritance. Top voted answer explains this finesse. About the reflection part, that sounds almost like a joke to me. Yes you can do that, you can also access those field values from processor cache or by breaking process memory boundaries and hacks like that. So I too think that the question was more about seeing your response then getting the right answer. I would personally say, that those fields are not part of CLASSES but part of OBJECTS.Ervin
Why not demonstrate the concept with code ?Pertinacity
Well, I think we should first figure out the meaning of "inheritance" in Java. The subclass does not have the private field and the subclass has the private field but cannot access to it are different, which one refers to the exact meaning of inheritance in Java?Kidnap
Well, you just pasted from the Javadoc half the truth. From the Javadoc the whole sentence says: "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."Depreciate
Moreover, "A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in"Depreciate
M
267

Most of the confusion in the question/answers here surrounds the definition of Inheritance.

Obviously, as @DigitalRoss explains an OBJECT of a subclass must contain its superclass's private fields. As he states, having no access to a private member doesn't mean its not there.

However. This is different than the notion of inheritance for a class. As is the case in the java world, where there is a question of semantics the arbiter is the Java Language Specification (currently 3rd edition).

As the JLS states (https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2):

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

This addresses the exact question posed by the interviewer: "do subCLASSES inherit private fields". (emphasis added by me)

The answer is No. They do not. OBJECTS of subclasses contain private fields of their superclasses. The subclass itself has NO NOTION of private fields of its superclass.

Is it semantics of a pedantic nature? Yes. Is it a useful interview question? Probably not. But the JLS establishes the definition for the Java world, and it does so (in this case) unambiguously.

EDITED (removed a parallel quote from Bjarne Stroustrup which due to the differences between java and c++ probably only add to the confusion. I'll let my answer rest on the JLS :)

Mathematical answered 17/1, 2011 at 18:11 Comment(14)
Sigh, so I guess in every language except Java, private fields are inherited but encapsulated. I disagree that derived classes have "no notion". It's simply that the compiler, which knows exactly what fields are there, generates an error message if you try to access them. The fact that it could perfectly well generate the code if it wanted kind of argues against the "no notion" notion.Laynelayney
@digital why the sigh. I understand you believe you are right. I don't disagree with you that object inheritance is what most programmers are taught/think about. But the JLS definition applies directly to the original question. It is semantics yes, but the JLS determines the definition, not you or I.Mathematical
One way to reconcile all this is to simply recognize that the word "inherit" is used in two very different ways to describe the relationship of derived and parent classes, at least in the Java world. Yes, the JSL is authoritive. Yes, it means you can use "inherit" in that unfortunate way. But it is still manifestly true that subclasses froggle (because now we don't have a word) the private fields of their parent class.Laynelayney
@digital They are in the object of the class. not the class itself. Simula called them concatenated objects. When an object of a subclass was created, it was made up of concatenated 'prefix objects'. The superclass object was a prefix object that could itself contain other prefix objects. I think it is arrogance to say that the JLS has "clearly bad wording". As for what word do we use, inheritance of course. There's nothing wrong with using slightly ambiguous terminology. It happens all the time. But that doesn't mean there isn't a precise definition.Mathematical
@digital We can certainly agree that the word is used in different ways. :) We can also probably agree that an interview question that depends on an ambiguous term is probably not a good one.Mathematical
I have updated my main answer to reflect that it's proper to say derived classes do not inherit private fields. If someone takes that literally, though, as some people here did, it will cripple their understanding of OOP.Laynelayney
@digital I agree with that completely. Only knowing a narrow definition is obviously not enough to understand OOP.Mathematical
It was not easy decision to accept answer. But I select this as it rest on JLSEgan
@stas Don't discount the other answers though. It's important to understand inheritance as a complete OOP topic. An interviewer is (should be) far more interested in your ability to use inheritance than your ability to remember a specific definition or semantics. When in doubt in an interview, elaborate.Mathematical
@RD01, I understand that sub class's instance contains private fields of their sups. But I don't think that they "inherits". There was discussion at interview about this topic. So I doubt in my opinion. I start this topic to check it. Now I understand that this interview has taught me some stuff)Egan
I always feel there are some access modification missing from java sand think that this page could add to explanation why javacamp.org/javavscsharp/access.htmlErvin
@Laynelayney - Yakshemash ! Can you please review my answer at - #4716540 Chenqui.Pertinacity
@Alkyne - Yakshemash ! Can you please review my answer at - #4716540 Chenqui.Pertinacity
Anyone has an reference from Java/Oracle for "Objects of subclass contain the private fields of their superclasses"? I agree with this, but cannot find any official documents saying that.Kidnap
L
91

Yes

It's important to realize that while there are two classes, there is only one object.

So, yes, of course it inherited the private fields. They are, presumably, essential for proper object functionality, and while an object of the parent class is not an object of the derived class, an instance of the derived class is mostly definitely an instance of the parent class. It could't very well be that without all of the fields.

No, you can't directly access them. Yes, they are inherited. They have to be.

It's a good question!


Update:

Err, "No"

Well, I guess we all learned something. Since the JLS originated the exact "not inherited" wording, it is correct to answer "no". Since the subclass can't access or modify the private fields, then, in other words, they are not inherited. But there really is just one object, it really does contain the private fields, and so if someone takes the JLS and tutorial wording the wrong way, it will be quite difficult to understand OOP, Java objects, and what is really happening.

Update to update:

The controversy here involves a fundamental ambiguity: what exactly is being discussed? The object? Or are we talking in some sense about the class itself? A lot of latitude is allowed when describing the class as opposed to the object. So the subclass does not inherit private fields, but an object that is an instance of the subclass certainly does contain the private fields.

Laynelayney answered 17/1, 2011 at 17:48 Comment(18)
+1. Because this is first answer with "Yes". But what do you think about javadoc?Egan
There is something inherently wrong in understanding inheritance like that. Definition of inheritance based around “reuse” of parent attributes or functionality. Since private members can not be reused by children, they can not be considered inherited.Pneumograph
+1. All instance of the sub-class have the field. If a field is not inherited by the sub-class, why is it there in instances of the sub-class. The field can be used by the sub-class, just not directly.Graf
@Ma99uS. Of course they are reused. That's the entire point of inheritance. Without them the derived type would not and could not be an instance of the parent type. OOP would be meaningless. Polymorphic types would stop working. Understanding that there is only one object and you ARE an instance of the parent type is crucial to understanding OOP. You must get past this issue to understand it at all.Laynelayney
Not sure the father example is very good because a field can be inherited while the parent class still lives and also has that field. If inheritance worked that way I could inherit my father's money while he's alive and he could keep the same money as well. My children would each have his money and my money.Graf
@Peter. There is only ONE OBJECT. There are two classes, yes, but the derived class IS an instance of the parent. The parent cannot "still live" and nothing can happen "while the parent still lives", because the derived object IS the parent object. It's JUST ONE. Without understanding this you cannot understand OOP.Laynelayney
The attribute is there, but is not inherited, that's the difference. Inheritance means, it could be threated as own ( accessed, modified, referenced, etc ) but this is NOT the case. See my answer.Alkyne
@Peter Lawrey not arguing or anything, but here is what I think. The parent had a car, he kept it in a private locker which the child does not the key of. You indeed inherit the car but it's useless to you. So, practically, you are not benefiting by inheritance.Pedestrianism
@DigialRoss I have to admit though, the reason why is there is very interesting!. But I'm pretty sure inheritance is not the answer, at least not it OO terms. It is the JVM who allocates that value but based totally in they parent definition. The attribute is owned by the parent, and the child is agnostic of it. For instance if you define: class A{private int i;} and class B extends A {} and look at B's byte code and you won't see any ref to i. Actually if you change the definition of A and eliminate the i the class B will still work. Demo pastebin.com/tsDDGdGBAlkyne
It does appear that in the Java world, thanks to wording originally in the JLS, it is occasionally said, including in the JLS, that "private fields are not inherited". But you cannot possibly understand OOP unless you realize that this is simply a way - a bad way - of stating that you can't directly access them. And the obvious problem with appropriating the word "inherit" is that there is now NO WORD to describe how those fields got into the derived class. And yes, it has to be in the derived class or it would not be in instances of the derived class.Laynelayney
@DigitalRoss. I get your point. Mhh, we could say the value is there because of the not inherited parent definition is also loaded. :) I think the JVM spec would have the correct answer for this "NO WORD" we are looking for. java.sun.com/docs/books/jvmsAlkyne
-1, The Java Language Specification clearly spells out that they are not inherited. No ifs, no buts. They are simply not. Any other definition of inheritance is wrong in the context of Java.Threesquare
@Laynelayney I fail to see how using the same word for two different things would help the situation though. The meaning of the word "inheritance" in Java couldn't be any clearer, as every single aspect of it is thoroughly defined. This is an often very underrated achievement of Java, and the fact some people don't bother to read the JLS and misunderstand some of the concepts is no reason for relaxing their thorough definition.Threesquare
@Oscar, regarding "class B will still work": maybe for any one example, but in general, removing a private superclass variable will have exactly the same effect on the child as it would on the parent. After all, there is only one object. Sure, you could inherit from an arbitrary superclass and then implement an unrelated object.Laynelayney
"There really is just one object, and if someone takes the JSL and tutorial wording literally, it will be quite difficult to understand OOP, Java objects, and what is really happening." -- I did not see anyone disagreeing on this on the whole thread. These are two perfectly alright point of views -- depends on whose glasses you're wearing -- the interviewer's or the interviewee in the OP. It's a word game, everyone knows what subclass gets when it's super has a private method. No one going to be bad programmer by staying on either side.Pedestrianism
I agree with you, just need to confirm that: the private methods of superclasses are also contained in the objects of subclasses, right?Kidnap
@Laynelayney I think inherited is different than knowing..!! Object knows about them but class didn't inherited them. ( Inheritance depend on Classes not Objects ) let me know if I'm wrong.Eschew
I think he is mixing encapsulation with inheritance.Depreciate
P
23

No. Private fields are not inherited... and that's why Protected was invented. It is by design. I guess this justified the existence of protected modifier.


Now coming to the contexts. What you mean by inherited -- if it is there in the object created from derived class? yes, it is.

If you mean can it be useful to derived class. Well, no.

Now, when you come to functional programming the private field of super class is not inherited in a meaningful way for the subclass. For the subclass, a private field of super class is same as a private field of any other class.

Functionally, it's not inherited. But ideally, it is.


OK, just looked into Java tutorial they quote this:

Private Members in a Superclass

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.

refer: http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html

I agree, that the field is there. But, subclass does not get any privilege on that private field. To a subclass, the private field is same as any private field of any other class.

I believe it's purely matter of point-of-view. You may mould the argument either side. It's better justify both way.

 

Pedestrianism answered 17/1, 2011 at 17:46 Comment(2)
This is not correct. You can't access them, that is correct. But they have to be inherited as I have explained.Laynelayney
excellent answer !!! +1 for I believe it's purely matter of point-of-view. and justified the existence of protected modifier.Alliterate
S
17

It depends on your definition of "inherit". Does the subclass still have the fields in memory? Definitely. Can it access them directly? No. It's just subtleties of the definition; the point is to understand what's really happening.

Sacrum answered 17/1, 2011 at 17:36 Comment(3)
Correct. But I think in such base question there should be common answers)Egan
I think it is the Java definition of inheritance.Alkyne
Or else it depends on your definition of "field". To define an integer field "foo" is to rent an integer-sized storage locker and put a "foo" sign on it. If the field is declared private, the derived class inherits an unlabeled integer-sized storage locker. Whether or not the derived class inherits the "field" depends upon whether one calls that unlabeled storage locker a "field".Miculek
P
12

I will demonstrate the concept with code. Subclasses ACTUALLY inherit the private variables of super class. The only problem is that they are not accessible to the child objects unless you provide public getters and setters for the private variables in the super class.

Consider two class in package Dump. Child extends Parent.

If I remember correctly, a child object in memory consists of two regions. One is the parent part only and the other is the child part only. A child can access the private section in the code of its parent only via a public method in the parent.

Think of it this way. Borat's father Boltok has a safe containing $100,000. He does not want to share his "private" variable safe. So, he does not provide a key for the safe. Borat inherits the safe. But, what good is it if he cannot even open it ? If only his dad had provided the key.

Parent -

package Dump;

public class Parent {

    private String reallyHidden;
    private String notReallyHidden;

    public String getNotReallyHidden() {
        return notReallyHidden;
    }

    public void setNotReallyHidden(String notReallyHidden) {
        this.notReallyHidden = notReallyHidden;
    }

}//Parent

Child -

package Dump;

public class Child extends Parent {

    private String childOnly;

    public String getChildOnly() {
        return childOnly;
    }

    public void setChildOnly(String childOnly) {
        this.childOnly = childOnly;
    }

    public static void main(String [] args){

        System.out.println("Testing...");
        Child c1 = new Child();
        c1.setChildOnly("childOnly");
        c1.setNotReallyHidden("notReallyHidden");

        //Attempting to access parent's reallyHidden
            c1.reallyHidden;//Does not even compile

    }//main

}//Child
Pertinacity answered 12/5, 2014 at 0:22 Comment(0)
A
11

No. They don't inherit it.

The fact some other class may use it indirectly says nothing about inheritance, but about encapsulation.

For instance:

class Some { 
   private int count; 
   public void increment() { 
      count++;
   }
   public String toString() { 
       return Integer.toString( count );
   }
}

class UseIt { 
    void useIt() { 
        Some s = new Some();
        s.increment();
        s.increment();
        s.increment();
        int v = Integer.parseInt( s.toString() );
        // hey, can you say you inherit it?
     }
}

You can also get the value of count inside UseIt via reflection. It doesn't means, you inherit it.

UPDATE

Even though the value is there, it is not inherited by the subclass.

For instance a subclass defined as:

class SomeOther extends Some { 
    private int count = 1000;
    @Override
    public void increment() { 
        super.increment();
        count *= 10000;
    }
}

class UseIt { 
    public static void main( String ... args ) { 
        s = new SomeOther();
        s.increment();
        s.increment();
        s.increment();
        v = Integer.parseInt( s.toString() );
        // what is the value of v?           
     }
}

This is exactly the same situation as the first example. The attribute count is hidden and not inherited by the subclass at all. Still, as DigitalRoss points out, the value is there, but not by means on inheritance.

Put it this way. If your father is wealthy and gives you a credit card, you can still buy thing with his money, but doesn't mean you have inherited all that money, does it?

Other update

It is very interesting though, to know why the attribute is there.

I frankly don't have the exact term to describe it, but it's the JVM and the way it works that loads also the "not inherited" parent definition.

We could actually change the parent and the subclass will still work.

For instance:

//A.java
class A {
   private int i;
   public String toString() { return ""+ i; }
}
// B.java
class B extends A {}
// Main.java
class Main {
   public static void main( String [] args ) {
      System.out.println( new B().toString() );
    }
}
// Compile all the files
javac A.java B.java Main.java
// Run Main
java Main
// Outout is 0 as expected as B is using the A 'toString' definition
0

// Change A.java
class A {
   public String toString() {
      return "Nothing here";
   }
}
// Recompile ONLY A.java
javac A.java
java Main
// B wasn't modified and yet it shows a different behaviour, this is not due to 
// inheritance but the way Java loads the class
Output: Nothing here

I guess the exact term could be found here: The JavaTM Virtual Machine Specification

Alkyne answered 17/1, 2011 at 17:39 Comment(7)
:) Next time you could take the chance to explain your interviewer where is he/she wrong, and this may give you extra points ;) Obviously you should do this in a diplomatic correct way.Alkyne
They have to be inherited for polymorphic types to have any meaning at all. See my explanation. It's true you can't fiddle with them, but they are there. They have to be.Laynelayney
There is no inheritance (extends/implements) keywords in your code so thats not an inheritance example.Watusi
@DigitalRoss, they are there, but not inherited.... mmhh let me you some code on this.Alkyne
Uhh, if they are there, how did they get there? Because the subclass defined them? No. Because they were, uhh, hmm, err, inherited?Laynelayney
Great point on encapsulation vs inherit, I guess this answer deserve more up vote.Outdoor
Thanks for your example, it means class child B refers to its parent methods and properties. That's why we don't have to recompile the class child, the JVM automatically allow the class child B see all the changes in class parent A which I mentioned "referenced".Earpiece
B
6

Well, my answer to interviewer's question is - Private members are not inherited in sub-classes but they are accessible to subclass or subclass's object only via public getter or setter methods or any such appropriate methods of original class. The normal practice is to keep the members private and access them using getter and setter methods which are public. So whats the point in only inheriting getter and setter methods when the private member they deal with are not available to the object? Here 'inherited' simply means it is available directly in the sub-class to play around by newly introduced methods in sub-class.

Save the below file as ParentClass.java and try it yourself ->

public class ParentClass {
  private int x;

  public int getX() {
    return x;
  }

  public void setX(int x) {
    this.x = x;
  }
}

class SubClass extends ParentClass {
  private int y;

  public int getY() {
    return y;
  }

  public void setY(int y) {
    this.y = y;
  }

  public void setXofParent(int x) {
    setX(x); 
  }
}

class Main {
  public static void main(String[] args) {
    SubClass s = new SubClass();
    s.setX(10);
    s.setY(12);
    System.out.println("X is :"+s.getX());
    System.out.println("Y is :"+s.getY());
    s.setXofParent(13);
    System.out.println("Now X is :"+s.getX());
  }
}

Output:
X is :10
Y is :12
Now X is :13

If we try to use private variable x of ParentClass in SubClass's method then it is not directly accessible for any modifications (means not inherited). But x can be modified in SubClass via setX() method of original class as done in setXofParent() method OR it can be modified using ChildClass object using setX() method or setXofParent() method which ultimately calls setX(). So here setX() and getX() are kind of gates to the private member x of a ParentClass.

Another simple example is Clock superclass has hours and mins as private members and appropriate getter and setter methods as public. Then comes DigitalClock as a sub-class of Clock. Here if the DigitalClock's object doesn't contain hours and mins members then things are screwed up.

Bans answered 3/9, 2013 at 22:43 Comment(1)
As per Oracle doc - 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.Bans
S
5

Ok, this is a very interesting problem I researched a lot and came to a conclusion that private members of a superclass are indeed available (but not accessible) in the subclass's objects. To prove this, here is a sample code with a parent class and a child class and I am writing child class object to a txt file and reading a private member named 'bhavesh' in the file, hence proving it is indeed available in the child class but not accessible due to the access modifier.

import java.io.Serializable;
public class ParentClass implements Serializable {
public ParentClass() {

}

public int a=32131,b,c;

private int bhavesh=5555,rr,weq,refw;
}

import java.io.*;
import java.io.Serializable;
public class ChildClass extends ParentClass{
public ChildClass() {
super();
}

public static void main(String[] args) {
ChildClass childObj = new ChildClass();
ObjectOutputStream oos;
try {
        oos = new ObjectOutputStream(new FileOutputStream("C:\\MyData1.txt"));
        oos.writeObject(childObj); //Writing child class object and not parent class object
        System.out.println("Writing complete !");
    } catch (IOException e) {
    }


}
}

Open MyData1.txt and search for the private member named 'bhavesh'. Please let me know what you guys think.

Skardol answered 31/5, 2012 at 10:57 Comment(0)
M
3

It would seem that a subclass does inherit the private fields in that these very fields are utilized in the inner workings of the subclass (philosophically speaking). A subclass, in its constructor, calls the superclass constructor. The superclass private fields are obviously inherited by the subclass calling the superclass constructor if the superclass constructor has initialized these fields in its constructor. That's just an example. But of course without accessor methods the subclass cannot access the superclass private fields (it's like not being able to pop the back panel of an iPhone to take the battery out to reset the phone... but the battery is still there).

PS One of the many definitions of inheritance that I have come across: "Inheritance -- a programming technique that allows a derived class to extend the functionality of a base class, inheriting all of its STATE (emphasis is mine) and behaviour."

The private fields, even if not accessible by the subclass, are the inherited state of the superclass.

Mosera answered 4/2, 2012 at 3:0 Comment(0)
S
3

For example,

class Person {
    private String name;

    public String getName () {
        return this.name;
    }

    Person(String name) {
        this.name = name;
    }
}
public class Student extends Person {

    Student(String name) {
        super(name);
    }
    
    public String getStudentName() {
        return this.getName(); // works
        // "return this.name;" doesn't work, and the error is "The field Person.name is not visible"

    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Bill");

        String name = s.getName(); // works
        // "String name = s.name;" doesn't work, and the error is "The field Person.name is not visible"

        System.out.println(name);
    }
}
Sedgewick answered 8/9, 2020 at 17:8 Comment(0)
L
2

Memory Layout in Java vis-a-vis inheritance

enter image description here

Padding bits/Alignment and the inclusion of Object Class in the VTABLE is not considered. So the object of the subclass does have a place for the private members of the Super class. However, it cannot be accessed from the subclass's objects...

Lymphoma answered 6/5, 2017 at 22:47 Comment(0)
I
1

No, private fields are not inherited. The only reason is that subclass can not access them directly.

Impermeable answered 8/1, 2013 at 5:3 Comment(0)
H
1

I would have to answer that private fields in Java are inherited. Allow me to demonstrate:

public class Foo {

    private int x; // This is the private field.

    public Foo() {
        x = 0; // Sets int x to 0.
    }

    //The following methods are declared "final" so that they can't be overridden.
    public final void update() { x++; } // Increments x by 1.
    public final int getX() { return x; } // Returns the x value.

}


public class Bar extends Foo {

    public Bar() {

        super(); // Because this extends a class with a constructor, it is required to run before anything else.

        update(); //Runs the inherited update() method twice
        update();
        System.out.println(getX()); // Prints the inherited "x" int.

    }

}

If you run in a program Bar bar = new Bar();, then you will always see the number "2" in the output box. Because the integer "x" is encapsulated with the methods update() and getX(), then it can be proven that the integer is inherited.

The confusion is that because you can't directly access the integer "x", then people argue that it isn't inherited. However, every non-static thing in a class, be it field or method, is inherited.

Hauck answered 26/2, 2015 at 23:39 Comment(1)
"Contains" doesn't mean "inherits" ;)Egan
A
0

I believe, answer is totally dependent on the question, which has been asked. I mean, if question is

Can we directly access the private field of the super-class from their sub-class ?

Then answer is No, if we go through the access specifier details, it is mentioned, private members are accessible only within the class itself.

But, if question is

Can we access the private field of the super-class from their sub-class ?

Which means, it doesn't matters, what you will do to access the private member. In that case, we can make public method in the super-class and you can access the private member. So, in this case you are creating one interface/bridge to access the private member.

Other OOPs language like C++, have the friend function concept, by which we can access the private member of other class.

Alliterate answered 30/11, 2012 at 12:53 Comment(0)
G
0

We can simply state that when a superclass is inherited, then the private members of superclass actually become private members of the subclass and cannot be further inherited or are inacessible to the objects of subclass.

Greenockite answered 25/3, 2013 at 17:57 Comment(0)
M
0

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses. https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

Moose answered 29/1, 2016 at 4:4 Comment(0)
W
0

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

reference: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html#:~:text=Private%20Members%20in%20a%20Superclass,be%20used%20by%20the%20subclass.

Wollastonite answered 22/7, 2020 at 5:19 Comment(0)
P
0

I can try to help you.
When a subclass(named B, for example) extends a superclass (named A, for example), it automatically inherits fields (such as attributes and/or methods) from its superclass.
Now, B in its Memory Layout has the space for every field in class A even the private ones. The fact is that Java doesn't allow the subclass B to use the private fields because they are private.

Portent answered 2/11, 2021 at 18:49 Comment(0)
L
0

As others have pointed out exerpt from JLS:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2:

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

The answer is NO without a doubt, without any iffs and buts. That revolves around the definition of inheritance. By definition inheritance is for classes, not for objects. Objects are created using class definitions. Inheritance is just another block to add to definition of a class. So, does a class inherits any private member of super class? NO

Litterbug answered 16/9, 2022 at 13:33 Comment(0)
S
-1

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.

Samekh answered 30/9, 2014 at 19:26 Comment(0)
W
-2

Private members (state and behavior) are inherited. They (can) affect the behavior and size of the object which is instantiated by the class. Not to mention that they are very well visible to the subclasses via all the encaptulation-breaking mechanisms that are available, or can be assumed by their implementers.

Although inheritance has a "defacto" definition, it definitely has no link to "visibility" aspects, which get assumed by the "no" answers.

So, there is no need to be diplomatic. JLS is just wrong at this point.

Any assumption that they are not "inherited" is unsafe and dangerous.

So among two defacto (partially) conflicting definitions (which I will not repeat), the only one that should be followed is the one that is safer (or safe).

Washtub answered 31/5, 2012 at 8:13 Comment(2)
-1. The JLS defines the language, it's impossible for the JLS to be "wrong". Also, if there are mechanisms that break the encapsulation, that does not mean the field is inherited; merely that there are mechanisms that subvert the encapsulation.Underlie
A definition can be by itself wrong in several ways. Discussing further on this is not my intention. The argument here is not on the mechanisms that break encapsulation (god or bad as they might be) but on the fact the field / method is there, affecting the behavior and state of your subclass. So it is "inherited". One could use a 100kb private byte array in a class and just assume that his (jumbo) descendants do not inherit it. Don't miss the point and judge this as a good or bad practice (exaggeration helps make a point): it is a foreseen, legitimate action. Private members ARE "inherited".Washtub

© 2022 - 2024 — McMap. All rights reserved.