Inheritance: Access to base class fields from a subclass

inheritance, java, oop

Solution

When you do `ChildClass childClassInstance = new ChildClass()` only one new object is created.

You can see the `ChildClass` as an object defined by:

- fields from `ChildClass` + fields from `ParentClass`.

So the field `strField` is part of ChildClass and can be accessed through `childClassInstance.strField`

So your assumption that

when the `ChildClass` constructor is called, an object of type `ParentClass` is created

is not exactly right. The created `ChildClass` instance is ALSO a `ParentClass` instance, and it is the same object.

Problem

How sub class objects can reference the super class? For example: ``` public class ParentClass { public ParentClass() {} // No-arg constructor. protected String strField; private int intField; private byte byteField; } public class ChildClass extends ParentClass{ // It should have the parent fields. } ``` Here when the `ChildClass` constructor is called, an object of type `ParentClass` is created, right? ChildClass inherits `strField` from the ParentClass object, so it (`ChildClass` object) should have access to `ParentClass` object somehow, but how?

Original source