iii
iii

Reputation: 626

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?

Upvotes: 0

Views: 72

Answers (1)

aliteralmind
aliteralmind

Reputation: 20163

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.

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.

Upvotes: 1

Related Questions