Determine the output:
public class Test1{
public static void main(String args[]){
ChildClass c = new ChildClass();
c.print();
}
}
class ParentClass{
int id = 1;
void print(){
System.out.println(id);
}
}
class ChildClass extends ParentClass{
int id = 2;
}
I know that the answer is 1, and I'm guessing that it's because since the print function isn't overridden in the ChildClass
, it has the same definition as it has in the ParentClass
. Why isn't the ID the one given in child class since Java uses late binding?
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
In Java inheritance we can access parent class properties via the child class object, as there is a keyword extends for achieving inheritance.
The class which inherits the properties of other is known as child class (derived class, sub class) and the class whose properties are inherited is known as parent class (base class, superclass class).
There is no dynamic dispatch on object fields, only on methods.
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