简体   繁体   中英

Its possible to define class as double type java?

I have the following class in java :

public class Percentage
{

    private double n;

    Percentage (double n )
    {
        this.n=n;
    }

    public void setN()
    {
        this.n=n;
    }

    public double getN()
    {
        return n;
    }

    public double percntage ()
    {
        return this.n/100;
    }
}

this Class Percentage will return a double value, but the problem is we can't make any mathematic operation with values like below:

public static void main (String args[])
{
    Percentage p = new Percentage(5);
    double b=1;
    b=p*12; // this is error because the class Percentage in not of type double
}

is there someway to make Percentage of type double ?

That is an error because you are multiplying the Percentage object with double value. The alternative is

public static void main (String args[])
{
    Percentage p = new Percentage(5);
    double b=1;
    b=p.getN()*12; 
}

You cannot make the class type double . You can perform your operation in the n value instead.

b = p.getN()*12; 

you can't define a class as double, because double is a primitive type. What you can do is what the others user suggested:

p.getN();

It will return the double value you need.

No, you can't make it behave like a double , but (like BigDecimal ) you can supply methods for performing the relevant operations.

Since your code seems to imply that n = 10 means 10% , ie a factor of 0.10 , you could make methods like these:

public double of(double value) {
    return value * this.n / 100d;
}

public double add(double value) {
    return value * (100d + this.n)) / 100d;
}

and then use it like this:

Percentage p = new Percentage(10);
double input = 55;
double d1 = p.of(input);  // 10% of 55 = 5.5
double d2 = p.add(input); // 55 + 10% = 60.5

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