Java Generic Learning notes-(iii) Generic methods

Source: Internet
Author: User

A generic method is similar to a generic class in that it defines a generic as a method, and the format is presumably:
  Public < Type parameters > return type method name (generic type variable name) {...}
The generic method is also divided into dynamic methods and static methods:
1. Dynamic generic methods I've actually used it in the previous blog post,

1  Public classBox<t> {2 3     PrivateT obj;4     5      PublicBox () {}6 7      PublicT getobj () {8         returnobj;9     }Ten One public   void  setobj (T obj) {A. obj =  obj; -  }  -  the      PublicBox (T obj) { -         Super(); -          This. obj =obj; -     } +  -}

The Setobj () is a generic method that uses only the generic parameters provided in the class. We can also define our own generic parameters for a generic method:

1  Public class Box<t> {23/     *... */ 4 5      Public void print (q q) {6        System.out.println (q); 7     }89 }

Note: Generic parameters are defined before the return value type.
This allows us to specify its own generics when the method is called:

1 New Box<>(); 2 b.<string>print ("Hello"); 3 //  //  Compile error

2. Static generic methods must specify their own type parameters when used, because static methods are loaded as the class loads. When a static method is loaded, there is no instance object for the class, so the type parameters provided by the class cannot be used:

 1  public  class  Box<t> 2  3  ...< /span>*/ 4  5  public  static  <Q>  print (q q) { 6   System.out.println (q); 
      7   " 8  9 } 

It is used in a similar way to dynamic methods.
3. Note : When calling a generic method that has its own type parameter specified, it is not necessary to explicitly specify its generic, and Java can infer the type of the generic at compile-time, such as:
Dynamic:

1 b.print ("Hello");

Static:

1 box.print ("Hello");

Because the incoming type is obviously a string, it is no longer specified.

Java Generic Learning notes-(iii) Generic methods

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.