Java:继承构造函数 [英] Java: Inherit constructor

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

问题描述

我希望有一个构造函数,其参数可以自动由所有子类继承,但Java不允许我这样做

I want to have a constructor with an argument that gets inherited by all child classes automatically, but Java won't let me do this

class A {
    public A(int x) {
     // Shared code here
    }
}

class B extends A {
    // Implicit (int x) constructor from A
}

class C extends A {
    // Implicit (int x) constructor from A
}

我不想要必须为每个子类编写 B(int x) C(int x)等。有没有更聪明的方法来解决这个问题?

I don't want to have to write B(int x), C(int x), etc. for each child class. Is there a smarter way of approaching this problem?

解决方案#1。创建一个 init()方法,该方法可以在构造函数之后调用。这是有效的,虽然对于我的特定设计,我想要求用户在构造函数中指定在编译时验证的某些参数(例如,不通过varargs / reflection)。

Solution #1. Make an init() method that can be called after the constructor. This works, although for my particular design, I want to require the user to specify certain parameters in the constructor that are validated at compile time (e.g. Not through varargs/reflection).

推荐答案

你做不到。如果你想在你的基类中有一个参数化的构造函数 - 而且没有无参数的构造函数 - 你必须在每个构造函数中定义一个构造函数(并调用 super()构造函数)。后裔类。

You can't. If you want to have a parameterized constructor in your base class - and no no-argument constructor - you will have to define a constructor (and call super() constructor) in each of descendant classes.

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

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