Java Fundamentals 4

Source: Internet
Author: User

1. Generic type

(1) Benefits of generics:

1, the original program to run when the problem may occur, the issue of conversion to compile time.

2, improve the safety of the program.

(2) Erase mechanism of generic type

Let the compiler block the insertion of illegal data into the collection at the source code level. But the compiler compiles a generic type of

Java program, the resulting class file will no longer have generic information. Simply put: Generics only work in the compile phase

Invalid run phase.

(3) Application of generic type

1. Declaring generics on a class

Class name <T> {}

Where can a generic declared on a class be applied?

Generics can be applied to instance properties, and instance methods.

Member of the class: member Property member method

Member Properties: Instance Attribute class properties

Member Methods: Instance method class methods

The generic type declared on a class cannot be applied to class properties, class methods, because class properties, class methods can be called directly through the class name, when generics do not have specific types. Class name. Attribute class name. method.

Generics can be applied to parameters and return values on a method.

public class genec<t>{

T T;

Public T Fun (t t1) {

  

}

}

2. Declaring generics on a method

What is the difference between declaring a generic and using a generic type?

Declare generic:<> when parentheses

Apply generics: Without parentheses

How do I declare generics on a method?

"Generic must be declared before the return value.

Public <T> void Fun1 (T T2) {

}

Java Fundamentals 4

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.