When do superclasses not have a default constructor?

前端 未结 3 1003
别那么骄傲
别那么骄傲 2021-01-19 16:32

According to the Java tutorial on constructors:

You don\'t have to provide any constructors for your class, but you must be careful when doing this.

3条回答
  •  隐瞒了意图╮
    2021-01-19 17:01

    And in the main method of a driver class you do

    A obj1 = new A();
    

    a default constructor will be created

    There is nothing you can do in the main method of a driver to create a default constructor. If it is defined, you can use it; if it is not defined, you get a compile error.

    So when will the superclass not have a no-argument constructor?

    When it has other constructors, all of which taking some arguments. Here is an example:

    class SuperA {
        public SuperA(String str) { ... }
        public SuperA(int num) { ... }
    }
    

    Above, SuperA has two constructors - one taking a String, and another one taking an int. Neither of them is default, because they take parameters.

    If you make a derived class DerivedB extends SuperA and do not define any constructors, you would get a compile error.

提交回复
热议问题