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?
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.
Single Inheritance - When a subclass inherits properties from one base class, it is called single inheritance.
No, a superclass has no knowledge of its subclasses.
Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.
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.
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 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 typeParentClass
is created
is not exactly right. The created ChildClass
instance is ALSO a ParentClass
instance, and it is the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With