java - Why is casting not working here as I expect? -


here sample code:

public class bar extends foo { }  @suppresswarnings("unchecked") public class foo {      public static void main(string[] args) {         foo foo = new bar();         class<foo> x = (class<foo>) foo.getclass();         system.out.println(x);     } } 

well expecting programs output be: foo.class since casting class see in output:

class bar 

why?

if remove casting part code, program not compile:

java: incompatible types required: java.lang.class<foo> found:    java.lang.class<capture#1 of ? extends foo> 

why compiler forcing me cast?

why?

because class of object bar, not foo (you created object new bar()), , you've explicitly asked the object class is. have foo reference object, doesn't change object is.

if remove casting part code, program not compile:

that's unrelated foo/bar thing. you've given x specific type (class<foo>), object#getclass typed class<?>.


from comment:

yes well, asked object itself, cased class<foo> , stored data in 'x'. confusing me..

casting has no effect on object @ all, casting purely changing type of reference have object. it's same object, unchanged, you've done change type of reference it. can change aspects of object have access to, , can (of course) fail if try cast object isn't.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -