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