Java-您可以重写类而不调用父类构造函数吗? [英] Java - Can you override a class w/o calling the parent class constructor?

查看:122
本文介绍了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
  }
}

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

I want to use this class, however I want to do different stuff in the constructor. The things that the constructor does I need to do them differently. But I want to use all the functionality of the other class methods.

我认为最简单的方法是扩展课程.但是,当我这样做时,构造函数要求我调用父构造函数:

I figured the easiest would be to extend the class. However when I do this, the constructor requires me to call the parent constructor:

super(url, something, whatever);

是否可以扩展基类但具有完全不同的构造函数?我根本不想调用BaseClass构造函数...

Is it possible to extend the base class but have a completely different constructor? I don't want the BaseClass constructor to be called at all...

推荐答案

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

You must invoke a constructor of the superclass. If you don't explicitly call one, Java will attempt to call the no-argument constructor automatically; if there is no such, you will get a compile error. The constructor you call does not need to correspond to the arguments passed to the subclass' constructor.

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

This is mandatory - objects' member variables can be initialized in a constructor, and not calling one of them could violate the superclass' internal assumptions.

除了使用JNI破坏JVM之外,没有其他方法.

There is no way around this short of using JNI to break the JVM.

这篇关于Java-您可以重写类而不调用父类构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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