Java-你能重写一个不调用父类构造函数的类吗



我有一个这样的类:

public class BaseClass
{
  public BaseClass(URL url, String something, String whatever)
  {
    // Do some stuff with URL, something and whatever
  }
  public List ImportantFunction()
  {
    // Some important stuff here
  }
}

我想使用这个类,但是我想在构造函数中做不同的事情。构造函数所做的事情我需要以不同的方式来做。但是我想使用其他类方法的所有功能。

我想最简单的办法就是扩展这个类。然而,当我这样做时,构造函数要求我调用父构造函数:

super(url, something, whatever);

是否可以扩展基类,但使用完全不同的构造函数?我根本不希望调用BaseClass构造函数。。。

您必须调用超类的构造函数。如果您没有显式调用一个,Java将尝试自动调用无参数构造函数;如果没有,您将得到一个编译错误。您调用的构造函数不需要与传递给子类构造函数的参数相对应。

这是强制性的——对象的成员变量可以在构造函数中初始化,不调用其中一个可能会违反超类的内部假设。

除了使用JNI破坏JVM之外,没有任何方法可以绕过这一点。

您将调用基类构造函数。如果你不想调用这个特定的构造函数,你必须定义一个默认的构造函数

public BaseClass(){ }

然后,当您进行扩展时,默认情况下会首先调用此构造函数。只有这样子类中的构造函数才会被调用。

您不必在父级中调用特定的构造函数。如果父级定义了默认构造函数,那么您可以执行以下操作:

public class ChildClass extends BaseClass {
    public ChildClass(URL url, String something, String whatever) {
        // implicit call to the Parent's default constructor if next line is commented
        super(); // explicit call to the default constructor of ParentClass
        // now do stuff totally specific to your ChildClass here
    }
 }

恐怕不行,你不可能不编辑超类的构造函数。然而,如果你担心这可能会影响现有的代码,你可以使用做以下事情,尽管我通常不建议这样做:

  1. 将所有构造函数代码移动到BaseClass中受保护的方法,比如protected void init(URL url, String something, String whatever){\constructor code}
  2. 从构造函数调用此方法

    public基类(URL URL、String something、String anything){init(URL URL,String something,String anything);}

  3. 在子类中重写此受保护的方法。

最新更新