Java中的默认构造函数 [英] Default constructors in Java

查看:174
本文介绍了Java中的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我在这里问了一些严肃的问题......

I know I'm asking some serious 101 question here...

我有一些课 Foo 以及扩展 Foo 的类 Bar 。在 Foo 中,我有一个构造函数,它接受一组设置到其字段的参数。派生诸如 Bar 之类的类通常不需要修改它。现在我的IDE给了我Foo中没有默认构造函数。从一点谷歌搜索看起来这似乎是因为构造函数不是继承的。所以一切都很好,但是我现在如何在不重复每个派生类的构造函数的情况下使用它?我假设有一个更合理的方法?

I have some class Foo and a class Bar that extends Foo. In Foo I have a constructor that takes a set of parameters that it sets to its fields. Deriving classes such as Bar will typically not need to modify this. Now my IDE is giving me "There is no default constructor available in Foo". From a bit of Googling this appears to be because "constructors are not inherited". So all nice and well, but how do I now get this to work without duplicating this constructor in every deriving class? I'm assuming there is a more sane approach?

推荐答案

使用 super 构造函数:

public Bar(int a, double b, ...) {
    super(a, b, ...);
}

这篇关于Java中的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆