Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

java - Why default constructor is required in a parent class if it has an argument-ed constructor?

Why default constructor is required(explicitly) in a parent class if it has an argumented constructor

class A {    
  A(int i){    
  }
}

class B extends A {
}

class Main {    
  public static void main(String a[]){
    B b_obj = new B();
  }
}

This will be an error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two aspects at work here:

  • If you do specify a constructor explicitly (as in A) the Java compiler will not create a parameterless constructor for you.

  • If you don't specify a constructor explicitly (as in B) the Java compiler will create a parameterless constructor for you like this:

    B()
    {
        super();
    }
    

(The accessibility depends on the accessibility of the class itself.)

That's trying to call the superclass parameterless constructor - so it has to exist. You have three options:

  • Provide a parameterless constructor explicitly in A
  • Provide a parameterless constructor explicitly in B which explicitly calls the base class constructor with an appropriate int argument.
  • Provide a parameterized constructor in B which calls the base class constructor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...