In Java, Why am I getting this error:
Error: The constructor WeightIn() is undefined
It's simply because you didn't have the matching constructor for your class:
public class WeightIn {
...
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
...
}
you need to add the public WeightIn() {}.
In Java, the default constructor is automatically generated by the compiler if you didn't defined it. So, when you define the following class:
public class WeightIn {
private double weight;
private double height;
// didn't define a constructor.
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
compiler will generating a matching default constructor for you. So, your class is implicitly having a default constructor like this:
public class WeightIn {
private double weight;
private double height;
// automatically generated by compiler
public WeightIn() {
// do nothing here.
}
// didn't define a constructor.
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
when you instantiate the class with:
WeightIn weight = new WeightIn();
everything is alright.
But when you're adding a constructor by yourself, the default constructor will not generated by the compiler. So, when you're creating the class with:
public class WeightIn {
...
// this won't automatically generated by compiler
// public WeightIn() {
// nothing to do here.
//}
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
...
}
You won't have the default constructor (i.e public WeightIn(){}). And using the following will raise an error because you have no matching constructor:
WeightIn weight = new WeightIn();
WeightIn()is not defined.