oli.G
oli.G

Reputation: 1350

Can't explicitly set a Long attribute by typing a number in Java

I've created a class that contains a Long attribute with a setter. When trying to use the setter to set the value to some random number, Idea tells me that actual argument int cannot be converted to Long by method invocation conversion.

This is my class:

public myClass() {

    private Long id;

    public Long getId() {
        return this.id;
    }

    public Long setId(Long id) {
        if(this.id == null)
            this.id = id;
        else throw new InvalidOperationException("Can't set more than once.");
    }

}

And somewhere else, I'm just trying to:

MyClass myInstance = new myClass();
myInstance.setId(15);

The build error hinted me to try a trick like this:

long newID = 17;
myInstance.setId(newID);

...which works. Only weird thing is, I have a different project open in NetBeans, and there's no compile error in an identical situation (and it's pretty safe to rule out any "outer" influences or unwanted interactions, it's all as simple as my code snippet here).

Could this be a compiler settings thing? I'd like to now a bit more about what's going on and why can't I just use myInstance.setId(15)

Upvotes: 1

Views: 1633

Answers (2)

Sushim Mukul Dutta
Sushim Mukul Dutta

Reputation: 777

If you are at all willing to pass an int then just do this edit.

int a=15;
myInstance.setId((long)a);

As Zim-Zam O'Pootertoot said a number by default is an int, hence you need to explicitly cast it to a long.

Upvotes: 1

Jean-Bernard Pellerin
Jean-Bernard Pellerin

Reputation: 12670

Try

myInstance.setId(15L);

When you use the long newID = 17; it knows it's expecting a long, when you do myInstance.setId(15);, it doesn't and so you need to be explicit.

Upvotes: 7

Related Questions