Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Error: The constructor is undefined

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.

like image 691
user2669883 Avatar asked Aug 10 '13 05:08

user2669883


People also ask

How do you fix a constructor that is undefined?

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 ).

Why is my constructor undefined Java?

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.

How do you define a constructor in Java?

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.

What happens when constructor is not defined?

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.


2 Answers

Add this to your class:

public WeightIn(){
}
  • Please understand that default no-argument constructor is provided only if no other constructor is written
  • If you write any constructor, then compiler does not provided default no-arg constructor. You have to specify one.
like image 78
Prasad Kharkar Avatar answered Oct 26 '22 01:10

Prasad Kharkar


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

like image 39
Ruchira Gayan Ranaweera Avatar answered Oct 26 '22 00:10

Ruchira Gayan Ranaweera