java - When would casting 'this' be required? -


are there situations in java require explicitly cast this type other current class?

class someclass {     void foo()     {         someotherclass s = (someotherclass) this;     } } 

edit: answers refer situations someotherclass sub-class of someclass, casting this can avoided in these situations proper oo design. looking situations oo can't out, i.e. someotherclass super-class of someclass.

there narrowing casts , widening casts. narrowing casts cast subtype or interface type, current type not declare implement. said yourself, should able avoid necessity of such cast proper oo design.

applying widening cast this should unnecessary given fact, reference type inherits members of superclass, exception of static members, not accessed via this anyway, , private members, can’t accessed cast. scenario widening cast of this might useful access field has been hidden field of same name:

class {     int foo; } class b extends {     int foo; } class c extends b {     {         ((a)this).foo=42;     } } 

note within b simple super.foo=42; sufficient, c requires type conversion access a.foo. and, of course, can avoid every widening cast introduction of variable of type, assigning makes widening conversion implicit:

a tmp=this; tmp.foo=42; 

another scenario might want call overloaded method passing this argument, want select overload accepts broader type or have select 1 because otherwise it’s ambiguous. still, can solved additional variable without type cast.

so, applying type cast this should always avoidable.

nevertheless, i’m not sure whether every developer strives “proper oo design” in every code (s)he writes. further, developer might prefer widening type cast on temporary variable sometimes.


Comments