What is java generic

Source: Internet
Author: User

What is generic?
First, we will write a simple generic class to illustrate:
[Java]
Public class Generics <T> {// T is short for type, which can be replaced by any name
Private T o; // generic member variable
Public Generics (T o ){
This. o = o;
}
Public T getObject (){
Return o;
}
Public void setObject (T o ){
This. o = o;
}
Public String getType (){
Return o. getClass (). getName ();
}
}
This generic class includes its own constructor, And the get, set, and getType methods.
We can use this class as follows:
[Java] www.2cto.com
Public class GenericsDemo {
Public static void main (String [] args ){

Generics <Integer> export bject = new Generics <Integer> (1 );
System. out. println ("the value of your bject is" + Your bject. getObject ());
System. out. println ("the type of your bject is" + Your bject. getType ());
 
Generics <String> stringObject = new Generics <String> ("hi, generics! ");
System. out. println ("the value of stringObjectis" + stringObject. getObject ());
System. out. println ("the type of stringObjectis" + stringObject. getType ());
}
}

We can use the versions of various types of this generic class (for example, Integer, String, and all Object classes and their subclasses ). However, generic data does not support basic data types.
Obviously, using java generics saves the need for forced type conversion. The compiler retains the type information of the parameter, performs the type check, and performs the type conversion operation. Therefore, developers do not need to ensure the security of type conversion, but leave this to the compiler.

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.