Key Java Technologies (20) characteristics of parametric types of generics

Source: Internet
Author: User

1.1. characteristics of parameterized types

Parameterized types have the following characteristics:

(1) There is no essential difference between a parameterized type and an original type without a type parameter after compilation.

(2) There are two parameterized types with different type parameters and cannot be mixed.

 Public classGenericparametertest {//parameterized type T, which can be a reference type such as String,integer. Static classSample<t> { //constructor with no arguments.  PublicSample () { This. obj =NULL;} PublicSample (T obj) { This. obj =obj;} //the type of the parameterized type as the return value.  PublicT work () {System.out.println ("Work:" + This. obj);return  This. obj;} //the parameterized type as the type of the parameter.  Public voidupdate (T obj) { This. obj =obj;} //the parameterized type as the type of the property. PrivateT obj;}  Public Static voidMain (string[] args) {//syntax error. Error usage. //sample<int> anothersample = new sample<int> (1);//correct usage. T is an integer.Sample<Integer> anothersample =NewSample<integer> (1); //correct usage: Do not use type parameters, equivalent to sample<string>. //you can now push the export type parameter to string. Sample Sam=NewSample ("Hello"); //error usage, you cannot convert a string to an integer.//Integer result = Sample.work ();//correct usage. String work ();String Result=sample.work ();//The original type.        Equivalent to sample<object> but different from sample<object>. //only the type parameter is inferred as object at this time. Sample SA=NewSample ();//error usage, cannot convert object to string.//String res = sa.work ();//correct usage. Object work ();Object Res=sa.work ();} 

Key Java Technologies (20) characteristics of parametric types of 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.