One of the explanations for the Java variable (covariant) return type------------base class and derived class

Source: Internet
Author: User

  In Java code, people assume that only one return value or no return can be returned in a method. Bloggers in the development process encountered such a situation, the Android client request data, the background may return two results (1) Access token invalidation, no data returned. (2) normal access to data.

  In such cases, it is necessary to determine whether there is data return based on the access token identity. Returns the user login prompt when it is invalid, and returns data when normal. Obviously, there are two kinds of results returned, and a method that only returns one type of imprisonment makes it slightly awkward to develop. make it very uncomfortable to develop.

  Think long and combine the inspiration of C + + covariant return type. Excerpt from the original: in C + +, as long as the original return type is a pointer or reference to a class, the new return type is a pointer or reference to the derived class, and the overridden method can change the return type . Such a type is called the covariant return type (covariant returns type).

  Because there is no pointer in Java, so the above function cannot be done. However, a derived class is a common method and a protection method that contains the parent class. Again, according to the principle of substitution of the Richter scale (where any base class can appear, subclasses must be able to appear), the base class must contain the base class property that the derived class contains, so the situation is much better. The base class method must be able to manipulate these properties as long as the derived class sets properties back into the base class . Then a complete variable return type can be set up. The following code is combined to verify:

First define two entity classes, the code is as follows,

  

1 classPerson {2     /**Suppose everyone has a name **/3 String name;4 5      PublicString GetName () {6         returnname;7     }8 9      Public voidsetName (String name) {Ten          This. Name =name; One     } A  -}// Person -  the classSupermanextendsPerson { -     /**Suppose every Superman has a height **/ -     intheight; -  +      Public intgetheight () { -         returnheight; +     } A  at      Public voidSetHeight (intheight) { -          This. Height =height; -     } -}//Superman

The Superman class inherits the person class (the blogger couldn't think of anything good at the time!). ), the Superman class contains the name and height two properties, and the base class person contains only the Name property.

Let's explain the normal way of operation, as a comparison. The code is as follows:

  

1  Public Static Person GetPerson1 () {2         New Person (); 3         Person.setname ("No Words"); 4         return Person ; 5     }

 1  public  static    Superman GetSuperMan1 () { 2  Superman Man = new   Superman ();  3  man.setname ("Do not Know"  4  man.setheight (120 5  return   man;  6 } 

Very simply, the return value is the expected return type, but if you replace the return type with the result. As shown below:

  

1  Public Static Superman Getsuperman () {2         New Superman (); 3         Person.setname ("Xiao Hu"); 4         return (Superman) person; 5     }

The above can only get Superman the Name property cannot get the Height property, if you return before returning strong to this plus the Height property, you can get a complete Superman object. This is no longer an attempt and the reader handles it itself.

  

1  Public Static Person Getperson () {2         New Superman (); 3         Man.setheight (+); 4         Man.setname ("Daming"); 5         return Man ; 6     }

The above code is the core of this article, but also to solve the problem at the beginning of the article. How does it work?

We write two classes, Erromessage and Datamessage classes, where Erromessage is the base class, Datamessage inherits the base class. Erromessage contains the Erromessage property type Private,datamessage contains the Data property. Then Erromessage only contains the Erromessage attribute, and the operation will only cause erromessage changes, without causing data changes. You can manipulate the Datamessage class only by manipulating the data property. In a method, as long as the method type is erromessage, the corresponding type can be returned as needed. When this method is used, all properties are obtained with derived classes, and if the subclass property is empty, the base class property must not be empty. If the derived class property is not empty, then the base class property must be empty. This makes it possible to obtain the appropriate data on demand. It's quite simple to operate. The code operates as follows:

  

1 printdivider ("person"); 2         Person person = Getperson (); 3         SYSTEM.OUT.PRINTLN ("Person's name is" + person.getname ()); 4         Superman Superman = (Superman) person; 5         System.out.println ("The Superman height obtained by strong transfer is like this" + superman.getheight ());

These are the bloggers ' understanding of the variable return type.

The core idea is this: a derived class can contain a common attribute of a base class, so the base class must be able to derive from the derived class the value that itself exposes to the derived class property . This is a reverse way of thinking, which may be contrary to the traditional way of writing code, but the software is to try to break the traditional thinking, even if the road is rugged. If there is any mistake, also hope that the readers put forward to criticize and grow together.

Finally Bo Master wrote a small demo, is: http://download.csdn.net/detail/tianqianya/8321397

The next time the variable return type of the interface is described. Please look forward to ^_^

2015-01-02

  

One of the explanations for the Java variable (covariant) return type------------base class and derived class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.