1) variableB is inherited in class B , for this reason onlyb.variableB prints a value.
2) Similarly I expect variableA to also be inherited in class B , however
I am able to define a new variable with the same name variableA , but with a different type ( the type is changed from int to boolean)
The compiler allows me to change the type of the inherited variableA to anything, why?
SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Originally posted by James Tharakan:
B onlyb = new B();
onlyb.variableA prints false.
I want to know is it possible for onlyb refernce to access the int variableA declared in the super class. ( i guess NO)
SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
When it's obvious that you have to do it, just do it without shattering your thoughts over different directions.
Originally posted by Henry Wong:
Well.... Technically, polymorphism only applies to methods, not instance variables. You are not overriding or inheriting the variables. These are two different variables, with the same name, and different type. You can still get to the variable of the base class, by casting to the base class, before dereferencing.
Now... I understand why you may think inheritence is occuring. If you use a variable that doesn't exist in the subclass, the compiler is smart enough to assume that you meant one of the variables in the base class, and generate the right code.
Henry
Originally posted by Rajshekhar Paul:
It's possible if you upcast the onlyb and assign it to A reference.
The above code will print 10.
And you can't directly access variableA of A class through B reference, because B is hiding the superclass version of variableA with it'S own version.