Home >Java >javaTutorial >How to define Java generic classes

How to define Java generic classes

王林
王林forward
2023-05-06 11:34:061945browse

1. Description

(1) To define a generic class, you only need to add type parameters after the class name. Of course, you can also add multiple parameters, such as similar, etc. Therefore, we can use defined type parameters in categories.

(2) The most commonly used usage scenario of generic classes is the use of tuples. We know that the return value of the method can only return a single object. If we define a general type and define two or even three type parameters, then build such a tuple data in our general type and transfer multiple objects through generics, so that we can use multiple data at one time.

2. Example

class DataHolder<T>{
    T item;
    
    public void setData(T t) {
     this.item=t;
    }
    
    public T getData() {
     return this.item;
    }
}

What is Java

Java is an object-oriented programming language that can write desktop applications, Web applications, Distributed systems and embedded systems applications.

The above is the detailed content of How to define Java generic classes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete