Hi,
Why is that I can access overriden methods in "sub" class but not variables?
Coming to the answer...
base B_class = new sub(); Here you are creating instance of sub class & assigning it to the base class reference variable.
So just imagine whatall things are there in this instance ( new sub(); ).
- int x=2;
- public void method_1 () { ..... }
- public void method_not_in_base() {.....}
- few other implicit methods (Ignore this point at the moment).
thats all we have in this instance.
Now You must be thinking
what happened to int x = 1 of base?
Ans:
variables are not inherited in java.Only methods are inherited.
Here in this instance you have overriden public void method_1 ()
which was inherited from base class.
why does it show error when we invoke method_not_in_base() {.....}?
Ans:
Though your instance has got method_not_in_base() but still you can
not access it,you know why because you are invoking it on the reference
variable of base class.
base B_class = new sub(); Here B_class is your reference variable of base class & new sub() is the instance of sub class.In other words your base class doesn't know
about method_not_in_base() because it is defined in the sub class.
However method_1(); can be invoked because base class knows that it has got method_1() method in it but since that method has been overriden in the sub class it will invoke it from sub class.
I hope this may help You.
If u have any queries or doubts you can ask...
One more thing when you post some code then try to maintain coding standard.
bkz Your code is quite confusing...
Thanks & Regards.
Waez.