I am studying overriding member functions in JAVA and thought about experimenting with overriding member variables.
So, I defined classes
public clas
OverRiding Concept in Java Functions will override depends on object type and variables will accessed on reference type.
For e.g.:
Parent parent=new Child();
parent.behaviour();
Here parent
is a reference of Parent class but holds an object of Child Class so that's why Child class function will be called in that case.
Child child=new Child();
child.behaviour();
Here child
holds an object of Child Class, so the Child class function will be called.
Parent parent=new Parent();
parent.behaviour();
Here parent
holds the object of Parent Class, so the Parent class function will be called.
When you trying to access the variable, it depends on the reference type object, not the object type.
For e.g.:
Parent parent=new Child();
System.out.println(parent.state);
The reference type is Parent so the Parent class variable is accessed, not the Child class variable.
Child child=new Child();
System.out.println(child.state);
Here the reference type is Child, so the Child class variable is accessed not the Parent class variable.
Parent parent=new Parent();
System.out.println(parent.state);
Here the reference type is Parent, so Parent class variable is accessed.