Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance: Access to base class fields from a subclass

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?

like image 759
Sina Barghidarian Avatar asked Mar 16 '13 17:03

Sina Barghidarian


People also ask

Can you inherit from a subclass?

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.

What is it called when a subclass inherits only one base class?

Single Inheritance - When a subclass inherits properties from one base class, it is called single inheritance.

Can superclass access subclass fields?

No, a superclass has no knowledge of its subclasses.

Can subclasses access superclass methods?

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.


2 Answers

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.

like image 179
Bastien Jansen Avatar answered Oct 18 '22 15:10

Bastien Jansen


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.

like image 26
ben75 Avatar answered Oct 18 '22 15:10

ben75