Home > Java > javaTutorial > How to define data types in Java

How to define data types in Java

WBOY
Release: 2023-04-21 11:16:09
forward
1663 people have browsed it

1. Explanation

There are two reasons why new T() cannot be used in generic code. One is that the type cannot be determined due to erasure; but it cannot be determined whether T contains No-argument constructor.

We use the factory pattern generic method to create instance objects, create IntegerFactory factories, and create Integer instances. If the code changes later, a new factory type can be added.

2. Example

/**
 * 使用工厂方法来创建实例
 *
 * @param <T>
 */
interface Factory<T>{
    T create();
}
 
class Creater<T>{
    T instance;
    public <F extends Factory<T>> T newInstance(F f) {
     instance=f.create();
     return instance;
    }
}
 
class IntegerFactory implements Factory<Integer>{
    @Override
    public Integer create() {
     Integer integer=new Integer(9);
     return integer;
    }
}
Copy after login

The above is the detailed content of How to define data types in Java. 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