Actual and Formal Arguments Vary in Length - Java Constructor Error

I am starting to learn Java and I am having a problem that I cannot solve. I have a class called MyClass with a constructor. I want this constructor to access a private field:

public class MyClass{
    private long variable1;
    public MyClass(long variable1){
        this.variable1=variable1;
    }
    public long somethingElse(Argument argument){
        return somevalue;
    }
    }

      

I can call somethingElse from another class when I remove the constructor. However, when I try something along the lines

data = new MyClass(); 
return data.somethingElse(argument);

      

I am getting an error in data = new MyClass () that the actual and formal arguments differ in length and "takes a long time, no arguments found". How to fix it?

+3


source to share


2 answers


From here :

The compiler automatically provides a default no-argument constructor for any class with no constructors



When you explicitly add a constructor, you override the default no-arg. So, to get it back, just add it manually:

public class MyClass{
    private long variable1;

    // This is what you need to add.
    public MyClass() {
    }

    public MyClass(long variable1){
        this.variable1 = variable1;
    }

    public long somethingElse(Argument argument){
        return somevalue;
    }
}

      

+3


source


The good thing is that you function somethingElse () is expected to return long. Therefore, if you are returning an argument that is being passed, you want it to be long as well. It would be pointless to say that you are returning a long and then passing an integer as an argument and returning it.

public long somethingElse(Argument argument){
    return somevalue; // have to make sure this is a long.
}

      

If this is not your problem, please give a more specific example of your problem, our actual code, so we can see what might be wrong.



Edit:

MyClass data = new MyClass(Some long here);

      

Make sure your constructor and the arguments it requires match what you are creating the data for. Once you declare your own constructor, the default constructor created will no longer be available to you.

+1


source







All Articles