Do I really need to define default constructor in java?

Viewed 52122

It works fine when constructors are not defined, but gives errors if I define a parameterized constructor and not a default one and not passing any values while creating an object. I thought constructors are predefined.

Why do I need to define a default constructor if I've defined a parameterized constructor? Ain't default constructor predefined?

6 Answers

There is also one curious case when you must define non argument constructor. As the other wrote, if you don't specify default constructor - Java will do it for you. It's good to understand how "default generated by Java" constructor looks like. In fact it calls constructor of the super class and this is fine. Let's now imagine one case. You are creating Vehicle class:

public class Vehicle {
private String name;
private String engine;

public Vehicle(String name, String engine) {
    this.name = name;
    this.engine = engine;
}

public String makeNoise(){
    return "Noiseee";
} 
}

As we can see Vehicle class has got only one defined 2 arguments constructor. Now let's create Car class which inheritates from Vehicle class:

public class Car extends Vehicle {

@Override
public String makeNoise() {
    return "Wrrrrrrr....";
}  }

Maybe it looks strange but only one reason why wouldn't it compile is fact that Java cannot create default constructor for Car class which call super Vehicle class. Vehicle class doesn't have no argument constructor and it cannot be generated automatically while 2 arg constructor already exists.

I know that it's very rare case, but I found it as a interesting to know.

Related