Java inheritance overriding instance variable
Instance variables are not overriden in sub-class
. If you define a variable in your class with the same name as in your super class it's called shadowing of variables inheritance and polymorphism
doesn't apply for instance variables. if you define method() in parent and override it in Child class. the below would invoke the Child's method() due to run-time polymorphism printing 11
parent p1 = new child();
- invokes Child constructor
- with the super() call invoke's parent's constructor
- Print's "in the parent" and initializes Parent's a to 10
print's in child and initializes Childs a to 11
p1.method();// this invokes Child's method() during run-time
Java instance variables cannot be overridden in a subclass. Java inheritance doesn't work that way.
In your example, there is no method hiding (or overriding or overloading) going on.
There is hiding of instance variables though. In class
child
, the declaration ofa
hides the declaration ofa
inparent
, and all references toa
in thechild
class refer to thechild.a
not theparent.a
.
To illustrate this more plainly, try running this:
public static void main(String args[]) throws IOException {
child c1 = new child();
parent p1 = c1;
System.out.println("p1.a is " + p1.a);
System.out.println("c1.a is " + c1.a);
System.out.println("p1 == c1 is " + (p1 == c1));
}
It should output:
p1.a is 10
c1.a is 11
p1 == c1 is true
This demonstrates that there is one object with two distinct fields called a
... and you can get hold of both of their values, if the access permits it.
Finally, you should learn to follow the standard Java identifier conventions. A class name should ALWAYS start with a capital letter.