Default constructors and inheritance in Java

2019-01-03 16:08发布

I have a question about default constructors and inheritance in Java.

Generally, if you write a class and do not include any constructor, Java provides automatically for you a default constructor (one without parameters), which initializes all instance variables of the class (if there are any) with some default values (0, null, or false). If you write a constructor, however, with some parameters, and you don't write any default constructor, then Java does not provide a default constructor. My question is: what is the case with classes, which inherit from other classes - if I write a constructor with some parameters in them, but don't include a default constructor, do they inherit the default constructor of the super class?

10条回答
该账号已被封号
2楼-- · 2019-01-03 16:47
  1. If you do not make a constructor, the default empty constructor is automatically created.

  2. If any constructor does not explicitly call a super or this constructor as its first statement, a call to super() is automatically added.

Always.

查看更多
闹够了就滚
3楼-- · 2019-01-03 16:50

Unless you use super(...) a constructor calls the empty constructor of its parent. Note: It does this on all you classes, even the ones which extend Object.

This is not inheriting, the subclasses don't get the same constructors with the same arguments. However, you can add constructors which call one of the constructors of the super class.

查看更多
Explosion°爆炸
4楼-- · 2019-01-03 16:51

There will be compile time error...because Compiler looks for default Constructor he Superclass and if its not there...its an error...and program will not Compile...

查看更多
贼婆χ
5楼-- · 2019-01-03 16:52

When we don't create a constructor Java creates a default constructor automatically. But when we create one or more custom constructors with arguments, Java doesn't create any default constructors. If we create one or more constructors and we want to create an object without any constructor arguments, we have to declare a empty constructor.

查看更多
登录 后发表回答