A tentative study of Java generics

Source: Internet
Author: User

In the Android project to see other people write the base class used in all kinds of generic, can understand and use. The feeling for Java learning is still a very important piece, in the future code career will encounter a lot, so brush a blog as a learning note.

Generics (Template) such as when you write a base class or API, because Java is a strongly typed language, you cannot anticipate what type of data will be used by the person who inherits the base class you write in the future, such as a string, an integer, or a class of his own definition. As a result, generics turned out (it's all my own opinion, why I didn't look for generics). The following example should be a good understanding of the role and use of generics.

1 classTemplate<t> {2      PublicT Getob () {3         returnob;4     }5 6      Public voidSetob (T ob) {7          This. OB =ob;8     }9 Ten     PrivateT ob; One  A      PublicTemplate (T ob) { -          This. OB =ob; -     } the      Public voidShowob () { -System.out.println (the type of OB is: "+Ob.getclass (). GetName ()); -     } - } +  - classShape { +     PrivateString color; A  at      PublicShape (String color) { -          This. color =color; -     } -  -      Public voidDraw () { -System.out.println ("Color is" +GetColor ()); in     } -  to      PublicString GetColor () { +         returncolor; -     } the  *      Public voidsetcolor (String color) { $          This. color =color;Panax Notoginseng     } - } the  +  Public classtemplatetest{ A  the      Public Static voidMain (string[] args) { +template<string> OB =NewTemplate<> ("88"); - Ob.showob (); $  $Template<shape> Shape =NewTemplate<> (NewShape ("RED")); - Shape.showob (); -     } the}

Output Result:

The type of OB is: Java.lang.Stringob type is: Shape

Here is an example where generics are implemented using string and custom shapes, which can be used on interfaces, abstract classes, and so on.

A tentative study of Java generics

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.