Wednesday 15 February 2012

java - Method chaining + inheritance don’t play well together? -


But I'm curious about Java worries about virtual methods (I think) do not apply, but if You have this status:

  Abstract class pet {Private string name; Public Pet Setnam (String Name) {this.name = name; This return; }} Stomach in class cats {public cat cat Amiss () {System.out.println ("I caught a mouse!"); This return; }} Dog dog expansion pet {public cat cat frisbe ({{System.out.println ("I caught a frisbee!"); This return; }} Square bird pet spreads {public bird leg () () {... back to it; }} {Cat C = new cat (); C.setName ("Morris") catchMice () .; // Error! Set name returns stomach, not kit dog d = new dog (); D.setName ("Snoopy") catchFrisbee () .; // Error! Set name returns stomach, not dog bird b = new bird (); B.setName ("Tweety") layEgg () .; // Error!  

In this type of hierarchy, is there any way to return this in such a way that is not effectively the object type?

If you want to avoid unchecked cast warnings from your compiler (do not use @SuppressWarnings ( "Uncontrolled"), then you need to do something else:

First of all, the definition of your pet should be referred to yourself, because the stomach is always a common type:

<

>

Put in the name To avoid this, use the "getThis" technique exquisite:

"getThis" conduction provides a way to recover the exact type of reference.

This results in the code given below, which compile and run without warnings. If you want to expand your subcategories, then the technique is still holding (though you may have your intermediate classes To generate Will be required).

The resulting code:

  public class Test {Class static abstract class belly & lt; T paste & lt; T & gt; & Gt; {Name of the private string; Protected abstract t getThis (); Public T Setnam (string name) {this.name = name; Return getThis (); }} Static class cat stomach & lt; Cat & gt; {@Override Protected Cat getThis (); Return to this; } Public Cat Mac () {System.out.println ("I caught a mouse!"); Return getThis (); }} Static class dog stomach & lt; Dog & gt; {@Override Protected Dog GetThis () {This Return; } To catch the public dog () {System.out.println ("I caught a frisbee!"); Return getThis (); }} Public static zero main (string [] args) {cat c = new cat (); C.setName ("Morris") catchMice () .; Dog D = new dog (); D.setName ("Snoopy") catchFrisbee () .; }}  

No comments:

Post a Comment