Inheritance: Access to base class fields from a subclass
Solution 1
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 fromParentClass
.
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 typeParentClass
is created
is not exactly right. The created ChildClass
instance is ALSO a ParentClass
instance, and it is the same object.
Solution 2
An instance of ChildClass
does not have a ParentClass
object, it is a ParentClass
object. As a child class, it has access to public and protected attributes/methods in its parent class. So here ChildClass
has access to strField
, but not intField
and byteField
because they are private.
You can use it without any specific syntax.
Solution 3
You can access strField
just as if it is declared in ChildClass
. To avoid confusion you may add a super.strField
meaning you are accessing the field in the parent class.
Solution 4
Yes, you will be able to access the strField
form the ChildClass
, 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).
Solution 5
here when the ChildClass constructor is called an object of type ParentClass is created, right?
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
the ChildClass inherits strField from the ParentClass OBJECT, so it (ChildClass object) should have access to ParentClass object somehow, but how?
No, it is just a reusing the template of ParentClass to creating new ChildClass
Sina Barghidarian
Updated on September 10, 2020Comments
-
Sina Barghidarian over 3 years
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 typeParentClass
is created, right?ChildClass inherits
strField
from the ParentClass object, so it (ChildClass
object) should have access toParentClass
object somehow, but how?