[英]How do I instantiate Generic types in Java?
package edu.uab.cis;
public class Fraction<Num> extends java.lang.Number{
private <Num> numerator;
private <Num> denominator;
public Fraction(Num num, Num denom)
{
this.numerator = num;
this.denominator = denom;
}
public double doubleValue() {
return 0;
}
public float floatValue() {
return 0;
}
public int intValue() {
return 0;
}
public long longValue() {
return 0;
}
public <Num> void number(Num num)
{
}
}
Im trying to create a generic type that will take all of the above primitive types so I can just use one method instead of using multiple ones. 我试图创建一个将接受所有上述原始类型的泛型类型,因此我只能使用一种方法而不是使用多种方法。 How can I correctly instantiate my method with the generic type so that it will take all number types and only number types? 如何正确地使用泛型类型实例化我的方法,以使其只接受所有数字类型,并且仅接受数字类型?
Change the class line to 将课程行更改为
public class Fraction<Num extends Number> extends java.lang.Number {
Eliminate the brackets around your variable declarations: 消除变量声明周围的括号:
private Num numerator;
And create a new instance with, for example 并创建一个新实例,例如
Fraction<Integer> intFrac = new Fraction<Integer>(1, 2);
And unless I'm misunderstanding you, you can eliminate the <Num> from the signature of your number(Num num)
function. 并且除非我对您有误解,否则您可以从number(Num num)
函数的签名中消除<Num>。
You should also consider changing Num
to N
, as a single capital letter is the convention for generics, and Num
can be confused as a class name. 您还应该考虑将Num
更改为N
,因为泛型的约定是单个大写字母,并且Num
可以混淆为类名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.