Why do I need to write a constructor here explicitly?

前端 未结 7 1879
無奈伤痛
無奈伤痛 2021-01-15 11:28

This is how I encountered the problem. I am giving an example:

package check;

public class Check {
  int a,b;
  Check (int i,int j) {
    a = i;
    b = j;
         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-01-15 11:59

    1) The compiler generates a no-arg constructor only if you don't define any constructor yourself. In class Check you have defined a constructor.

    2) If you don't explicitly call a super class constructor in a constructor that you define, the compiler generates a call to a no-arg constructor. Since class Check doesn't have a no-arg constructor, the compiler can't generate the call and you must write it yourself.

    You might be wondering why the constructor of a class must call the constructor of its parent. This is to ensure that the object is fully initialized before you try to use it: the parent constructor may initialize some aspect of the object that is only accessible to itself, and calling the constructor when the object is created is the only way to ensure proper initialization.

提交回复
热议问题