java - Overriding with Superclass Reference for Subclass Object -
i have been moving through couple of books in order teach myself java , have, fortunately, due luck, encountered few difficulties. has changed.
i read section on following under inheritance , whole superclass subclass setup
-- when new superclass object created, is, objects, assigned reference (superreference in example)
-- if new subclass object (with defining subclass extending superclass) created, , superreference reference set refer instead of original object, understanding that, since reference made superclass, members defined superclass may accessed subclass.
first - correct?
second: if overriding method , therefore have 1 in super , 1 in sub, , create superclass object , assign reference, did above, subclass object, principle called dynamic method dispatch, called overridden method should default accessing subclass method right?
well, question is:
if reference superclass-object retooled subclass-object , deny direct object.member access subclass-defined members, supporting superclass-defined members, how can, if superclass reference retooled subclass object, overridden method apply subclass-object if access limited superclass-originated-reference-
if try like:
class superclass{ int intvar = 0; void method(){ //in super class } } class subclass extends superclass{ int intvar = 2; void method(){ //in sub class } }
then
superclass obj = new subclass(); int val = obj.intvar;// taken superclass variables decided on reference basis //if both superclass , subclass contain same variable called shadowing obj.method();// taken subclass method overriding //and decided @ runtime based on object not reference
check comments. hope helps.
Comments
Post a Comment