In Spring boot if we are creating a POJO class and we end up creating only a parameterized constructor and not any default constructor then Java will throw errors, why does this happen if Java provides a non-parameterized constructor by default why do I still have to implement it manually?
I tried not creating a non-parameterized constructor for a POJO and it threw an error when I created an object of the POJO class in another class.
In Java, if you don't provide any constructor explicitly in your class, Java provides a default constructor. However, there's an exception to this rule. If you define any constructor explicitly in your class, Java won't provide a default constructor for you.
public class Employee{
// No constructor defined explicitly
// Other class members and methods
}
In this case, since no constructor is explicitly defined, Java will provide a default constructor for the Employee class.
However, if you define any constructor in your class, then Java won't provide a default constructor. For example:
public class Employee{
String name;
public Employee(String name) {
// Constructor with parameter
}
// Other class members and methods
}
In this case, since a constructor is explicitly defined (Employee(String x)), Java won't provide a default constructor for Employee. If you need a default constructor along with your parameterized constructor, you'll need to define it explicitly:
public class Employee{
String x
public Employee(String name) {
// Constructor with parameter
}
public Employee() {
// Default constructor
}
// Other class members and methods
}
Now, the Employee has both a parameterized constructor and a default constructor.