Home > Java > javaTutorial > body text

How to define Java generic classes

王林
Release: 2023-05-06 11:34:06
forward
1913 people have browsed it

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;
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!