gpt4 book ai didi

java - 如何编写一个构造函数来阻止在某些条件下创建对象

转载 作者:行者123 更新时间:2023-11-30 03:04:23 25 4
gpt4 key购买 nike

我正在尝试为继承另一个对象的对象创建一个构造函数,但此构造函数还应该在某些条件下阻止创建该对象。

我有这个代码:

class Foo
{
double x;
public Foo(double init_x)
{
x = init_x;
}
}

class Bar extends Foo
{
public Bar(double init_x)
{
if(init_x < 10)
{
throw new Exception();
}
super(init_x);
}
}

以下是使用 main 定义编译代码时出现的错误:

test2.java:13: error: constructor Foo in class Foo cannot be applied to given types;
{
^
required: double
found: no arguments
reason: actual and formal argument lists differ in length
test2.java:18: error: call to super must be first statement in constructor
super(init_x);
^
2 errors

我的问题是:即使我明确指定了 Bar(double init_x) ,为什么我还是收到了第一个错误,并且对于第二部分,如果 super 调用必须是第一个语句,那么如何做我解决这个问题了吗?

最佳答案

您有两个选择:

  1. 您将支票移至调用 super 之后。它仍然在方法完成之前,因此调用者将看不到构造的对象 - 它至少在调用者的 View 中阻止了构造:

    class Bar extends Foo {
    public Bar(double init_x) throws Exception {
    super(init_x);
    if (init_x < 10) {
    throw new Exception();
    }
    }
    }
  2. 您在另一个方法中进行检查,该方法返回值(如果正确),但如果不正确则抛出异常:

    class Bar extends Foo {
    private static double checkInitX(double init_x) throws Exception {
    if (init_x < 10) {
    throw new Exception();
    }
    return init_x;
    }

    public Bar(double init_x) throws Exception {
    super(checkInitX(init_x));
    }
    }

    您可以在对 super 的调用中作为表达式进行调用,该方法不是您正在构造的对象上的实例方法。放置该方法的一个好地方是作为类中的静态方法。

但通常情况下,选项 1 是最好的。除非有充分的理由不使用超出范围的值调用 super(例如,super 构造函数非常慢,或者如果值超出范围,它会抛出另一个令人困惑的异常),否则选项 2 是不必要。 (在提到的两种情况下,最好重构父类(super class)构造函数)

关于java - 如何编写一个构造函数来阻止在某些条件下创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com