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?
An instance of
ChildClass
does not have aParentClass
object, it is aParentClass
object. As a child class, it has access to public and protected attributes/methods in its parent class. So hereChildClass
has access tostrField
, but notintField
andbyteField
because they are private.You can use it without any specific syntax.
Yes, you will be able to access the
strField
form theChildClass
, without performing any special action (note however that only one instance will be created. The child, which will inherit all properties and methods from the parent).When you do
ChildClass childClassInstance = new ChildClass()
only one new object is created.You can see the
ChildClass
as an object defined by:ChildClass
+ fields fromParentClass
.So the field
strField
is part of ChildClass and can be accessed throughchildClassInstance.strField
So your assumption that
is not exactly right. The created
ChildClass
instance is ALSO aParentClass
instance, and it is the same object.No! ChildClass constructor is called >> parent class constr is called and No Object of the ParentClass is created just accessible field from the parent class are inherited in ChildClass
No, it is just a reusing the template of ParentClass to creating new ChildClass
By focusing on the business of non-arg constructor and compiler's involvement only, while the derived class(
ChildClass
)'s default constructor(non-arg constructor) is being invoked, a subobject of base class(ParentClass
) is created through the mechanism of compiler's help(insert base class constructor calls in the derived class) and wrapped within the derived class's object.result:
You can access
strField
just as if it is declared inChildClass
. To avoid confusion you may add asuper.strField
meaning you are accessing the field in the parent class.