Java-Aware generics

Source: Internet
Author: User

First, generics are the new features added after JDK1.5. Generics (Generic)

Avoids frequently occurring data type conversion exceptions

Second, generics can solve the security problem of data type, its main principle is that when the class declaration through an identity to represent the type of a property in a class or the return value of a method and the parameter type.

Third, format

Access Permissions class class name < Generics, generics ... >{property method}

Iv. Creation of objects

Class name < concrete type > Object name = new class name < concrete type > ();

Five, the Code demonstration

Class Point<t>{private T x;private T y;public T GetX () {return x;} public void SetX (T x) {this.x = x;} Public T GetY () {return y;} public void Sety (T y) {this.y = y;}} public class GenericDemo01 {public static void main (string[] args) {point<string> PS = new point<string> ();p S. SetX ("Longitude is ten");p s.sety ("Latitude of 100"); System.out.println (Ps.getx () + "" +ps.gety ()); point<integer> PI = new point<integer> ();p I.setx (Ten);p i.sety (100); System.out.println ("Longitude:" +pi.getx () + "Latitude:" +pi.gety ()); point<float> PF = new point<float> ();p f.setx (10.0f);p f.sety (100.0f); System.out.println ("Longitude:" +pf.getx () + "Latitude:" +pf.gety ());}}

Execution Result:

Longitude is 10 latitude is 100 Longitude: 10 Latitude: 100 Longitude: 10.0 Latitude: 100.0


Java-Aware 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.