Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of using Java generics

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

The main content of this article is "Java generics use case analysis", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "Java generics use case analysis" bar!

1. Overview

As an object-oriented programming language, Java can facilitate our use by implementing some classes as a template for our various requirements. But sometimes, the scope of this class may be larger than we want, and we only want to limit it to certain objects of the class, in which case the concept of generics is proposed (unofficial interpretation, easy to understand).

For example: for example, the car in our life, it can be used as a class, but there are actually many kinds of cars, including trucks, cars, buses and so on, and the cars in them are similar in appearance, but belong to different brands. There are many differences in these brands, and here we can think of car brands as generic (similar to labels).

Through the above explanation, the concept of generics is clearer, which is a kind of "type parameter". The so-called type parameter can be understood as parameterizing the type from the original specific type, similar to the variable parameters in the method. At this time, the type is also defined as a parameter form (can be called a type parameter), and then the specific type (type argument) is passed in when using / calling.

The advantages of generics are not only mentioned above, but also have the following advantages:

Type safety: improve the type safety of Java programs (the main goal of generics).

By knowing the type limits of variables defined using generics, the compiler can verify the type hypothesis.

Eliminate cast: eliminate many cast in source code.

This makes the code more readable and reduces errors

The above mentioned the use of generics in classes, in fact, the use of generics is much more than that, it can also be used in interfaces and methods. Let's introduce these separately.

two。 Generic class

The so-called generic class is that when we declare a class, the type of some members of the class is not determined, and then we can define the generic type on the class, and then clarify the type of the uncertain member when using this class.

Syntax format:

[modifier] class class name {

/ / Class body

}

Note: it can be one or more type variables, usually represented by a single uppercase letter. For example:, etc.

Type variables in cannot be used on static members.

Use of generic classes:

When using a class similar to a parameterized type, we need to be aware of when creating objects for the class:

Specify the actual type parameters corresponding to the type variables

The actual type parameter must be a reference data type, not a basic data type

Note: when specifying generic arguments, the left and right sides must be the same, and there is no polymorphism (the one on the right can be omitted)

Code example:

Declaration and use of generic classes:

Public class Demo1 {public static void main (String [] args) {/ / use of generic classes (which can only be of reference types) Student student1 = new Student ("Student 1", 99.5); Student student2 = new Student ("Student 2", "excellent"); Student student3 = new Student ("Student 3",'A'); / / output result System.out.println (student1) System.out.println (student2); System.out.println (student3);}} / / declaration of the generic class class Student {/ / this is the type parameter private String name; private T score of the generic class / / use generics to define scores (scores may have double type (99.5), string type (excellent), character type ('A'), etc.) / / constructor public Student () {} public Student (String name, T score) {this.name = name; this.score = score } @ Override public String toString () {return "Student {" + "name='" + name +'\'+ ", score=" + score +'}';}} 2.1generic interface

Generic interfaces and generic class relationships, just like interfaces and classes. There's not much to say here.

Syntax format:

[modifier] interface interface name {

}

Note: it can be one or more type variables, usually represented by a single uppercase letter. For example:, etc.

Type variables in cannot be used on static members.

2.2 use of generic interfaces

When using an interface similar to a parameterized type, we need to be aware of:

Specify the actual type parameters corresponding to the type variables

The actual type parameter must be a reference data type, not a basic data type

Code example

Declaration and use of generic interfaces:

Public class Demo1 {public static void main (String [] args) {/ / use of generic classes (which can only be reference types) Student student1 = new Student ("Student 1", 99.5); / / use generic interface student1.print ("Student 1", 99.5) }} / / the declaration of the generic class class Student implements Print {/ / this is the generic class, followed by the interface. Multiple type variables private String name; private T score; / / use the generic / / constructor public Student () {} public Student (String name, T score) {this.name = name; this.score = score } / / the method of rewriting the interface @ Override public void print (String s, T t) {System.out.println ("student name:" + this.name); System.out.println ("student score:" + this.score);}} / / the declaration of the generic interface interface Print {/ / defines a print function that can print the student name and grade public void print (T t, V v) } 3. Upper and lower limits of type variables

As mentioned earlier, we can use generic type parameters so that when we actually use them, we can use types as we like, but generics can also be implemented if we want to use only a series of types. This is what we call the upper limit of type variables and the lower limit of type variables. The following are introduced separately.

3.1 Upper limit of type variables

If a generic class defines an upper limit for type variables, then the actual type of the generic class can only be the upper limit type or its subclass type.

Syntax format:

Generic classes and generic methods are used the same way, and no distinction is made later.

/ / there can be multiple caps.

Note: if there are classes in multiple upper limits that have interfaces, then there can only be one class, and it must be written on the far left. If there are interfaces, there can be more than one.

If no upper limit is specified at the time of the declaration, the default upper limit is java.lang.Object.

Code example:

Upper limit of type variables:

Public class Demo2 {public static void main (String [] args) {Test test1 = new Test (77.5); / / double class / / Test test2 = new Test (); not a subclass of the number class Test test3 = new Test (18); test1.print (77.5); test3.print (18);}} class Test {/ / number class upper limit, can only use the number class and its subclass private T num Public Test () {} public Test (T num) {this.num = num;} public void print (T num) {/ / Test method System.out.println (num);} lower bound of type variables

If a generic class defines a lower bound of a type variable, the actual type of the generic class can only be the lower bound type or its parent class type.

Syntax format:

Any type

Any type

When generics use this type wildcard, it means that any type can be used

Code example:

/ * Type wildcard * / public class Demo4 {public static void main (String [] args) {/ / when used by Chinese teachers: StudentInfo stu1 = new StudentInfo ("Zhang San", "good"); / / when used by math teachers: StudentInfo stu2 = new StudentInfo ("Zhang San", 90.5) / / when used by English teachers: StudentInfo stu3 = new StudentInfo ("Zhang San",'C'); StudentInfo [] arr = new StudentInfo [3]; / / use the wildcard characters arr [0] = stu1; arr [1] = stu2; arr [2] = stu3; StudentInfoPrint.print (arr) / / print the result}} / / the student class is a parameterized generic class class StudentInfo {private String name; private T score; public StudentInfo () {super ();} public StudentInfo (String name, T score) {super (); this.name = name; this.score = score } @ Override public String toString () {return "name:" + name + ", score:" + score;}} / / Student information printing class class StudentInfoPrint {/ / generic method, using the wildcard public static void print (StudentInfo [] arr) {for (int I = 0; I < arr.length; iTunes +) {System.out.println (arr [I]) At this point, I believe you have a deeper understanding of "Java generics usage case analysis". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report