简体   繁体   中英

java and interfaces implementing different parameter types

I'm working on a basic math interface and wondering if there's a way I can specify that the type parameter can only be an integer or float without using the type?

for example, this is the basic layout, where is is where I'm trying to say Integer or Float without hard coding it into the actual abstract method.

public interface Math<T> {

    T add(T t, T r);
}

Thanks

There is no way to restrict the type of a generic to a specific few but you could just require a float since floats will behave like integers

Using <T extends Number> can restrict this to Number or its subclasses. You can check https://docs.oracle.com/javase/tutorial/java/generics/bounded.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM