Reputation: 101
I am starting to learn Java and I ran into a problem that I can't solve. I have a class called MyClass with a constructor. I want to set that constructor to access the 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 get an error at data = new MyClass() that actual and formal arguments differ in length and "requires long, found no arguments". How do I fix this?
Upvotes: 3
Views: 442
Reputation: 850
Well you function somethingElse() is expected to return a long. So if you are returning the argument that is passed in, you want it to also be a long. It wouldn't make much sense to say you are returning a long and then pass in a integer as the argument and return that.
public long somethingElse(Argument argument){
return somevalue; // have to make sure this is a long.
}
If this isn't your problem, please give a more concrete example of your problem, our your actual code so we can see what could be going wrong.
Edit:
MyClass data = new MyClass(Some long here);
Make sure your constructor and the arguments it requires matches what you are instantiating data to. As soon as you declare your own constructor, the default constructor that is generated is not longer available to you.
Upvotes: 1
Reputation: 695
From here:
The compiler automatically provides a no-argument, default constructor for any class without constructors
When you explicitly add a constructor, you override the default no-arg one. 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;
}
}
Upvotes: 3