In Java, Why am I getting this error:
Error: The constructor WeightIn() is undefined
Java Code:
public class WeightIn{
private double weight;
private double height;
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
public class WeightInApp{
public static void main (String [] args){
WeightIn weight1 = new WeightIn(); //Error happens here.
weight1.setWeight(3.65);
weight2.setHeight(1.7);
}
}
I have a constructor defined.
To fix it, perform an undefined check on the variable before trying to access the constructor property. Using the optional chaining operator on a variable will return undefined and prevent the property access if the variable is nullish ( null or undefined ).
this compilation error is caused because the super constructor is undefined. in java, if a class does not define a constructor, compiler will insert a default one for the class, which is argument-less. if a constructor is defined, e.g. super(string s), compiler will not insert the default argument-less one.
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object.
However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.
Add this to your class:
public WeightIn(){
}
With your current implementation, you can't do WeightIn weight1 = new WeightIn();
since default constructor is not defined.
So you can add
public WeightIn(){
}
Or you can do this
WeightIn weight1 = new WeightIn(3.65,1.7) // constructor accept two double values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With