java的无参构造函数,如何一个Java类没有无参构造函数?

The Oracle Java tutorial site has this paragraph that is confusing me:

All classes have at least one

constructor. If a class does not

explicitly declare any, the Java

compiler automatically provides a

no-argument constructor, called the

default constructor. This default

constructor calls the class parent's

no-argument constructor, or the Object

constructor if the class has no other

parent. If the parent has no

constructor (Object does have one),

the compiler will reject the program.

If all objects directly or indirectly inherit from Object how is it possible to elicit the compiler rejection spoken of? Does it have to do with the constructor being private?

解决方案

If all objects directly or indirectly inherit from Object how is it possible to elicit the compiler rejection spoken of?

I think the basis is of your misunderstanding is that you are thinking that constructors are inherited. In fact, constructors are NOT inherited in Java. So consider the following example:

public class A {

public A(int i) { super(); ... }

}

public class B extends A {

public B() { super(); ... }

}

The class A:

does not inherit any constructors from Object,

does not explicitly declare a no-args constructor (i.e. public A() {...}), and

does not have a default constructor (since it does declare another constructor).

Hence, it has one and only one constructor: public A(int).

The call to super() in the B class tries to use a non-existent no-args constructor in A and gives a compilation error. To fix this, you either need to change the B constructor to use the A(int) constructor, or declare an explicit no-args constructor in A.

(Incidentally, it is not necessary for a constructor to explicitly call a superclass constructor ... as I've done. But a lot of people think it is good style to include an explicit call. If you leave it out, the Java compiler inserts an implicit call to the superclasses no-args constructor ... and that results in a compilation error if the no-args constructor does not exist or is not visible to the subclass.)

Does it have to do with the constructor being private?

Not directly. However, declaring a constructor private will prevent that constructor being called from a child class.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值