it prints : B.s1 A.s2 A.s1 A.s2 I thought it printed: B.s1 A.s2 B.s1 A.s2 why? Is variable s1 in class B hiding s1 in class A? how's the procedure to figure this out.. when you extend a class are you inheriting all non-private members (instance variables, methods)?
I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
when you extend a class are you inheriting all non-private members
yes. except those which have hided any super class members.
how's the procedure to figure this out..
only instance methods are overriden. Super s = new Sub(); s.m(); // will call sub's m IF it is overriden. on the other hand feilds are shadowed. feilds are accessed using the reference variable type. Super s = new Sub();// ref var is Super s.aField; // will access S's aField Sub s = new Sub(); Super sup = (Sup)s; sup.aField; // will still access S's aField because the variable 'sup' reference type is Sup and not Sub. In order to access Super's hidden feilds through Sub refernece, u can 'cast' to Super. Sub s = new Sub(); int aField = ((Sup)s).aField;// now will access Sup's even if it is shadowed in Sub. hope it helps. [ June 07, 2003: Message edited by: G Nadeem ]
Well, technically speaking, the term should be shadowing.
If a class declares a field with a certain name , then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in super classes,and superinterfaces of the class
JLS 2Ed 8.3 pp153-154
A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occures throughout the scope of d
JLS 2Ed 6.3.1 p86. so i think in above case is that of hiding and not shadowing. am i making any mistake here?..