简体   繁体   English

从派生类调用构造函数

[英]calling a constructor from a derived class

Hi I have been trying to use my zeroparameter constructors to call my SunkenObject constructor with initial weight values but for some reason i keep getting this error 嗨,我一直试图使用我的zeroparameter构造函数来调用具有初始权重值的SunkenObject构造函数,但是由于某些原因,我一直收到此错误

constructor SunkenObject in class SunkenObject cannot be applied to given types ;` in class SunkenObject中的constructor SunkenObject不能be applied to given types

required: float
  found: no arguments
  reason: actual and formal argument lists differ in length

This is my SunkenObject constructor: 这是我的SunkenObject构造函数:

public abstract class SunkenObject extends CatchableThing
{
   protected float weight;

   public SunkenObject(float w)
   {
     weight = w;
   }

  public float getWeight() { return weight; }

    public String toString () 
    {
        return (getClass().getSimpleName());
    }
}

and this is one of the objects (a rusty chain) that is extended by SunkenObject 这是SunkenObject扩展的对象(生锈的链)之一

public class RustyChain extends SunkenObject 
{

    public RustyChain (float w)
  {
    super(w);  
  }
   public RustyChain()
   {
     weight = 8.0f;
   }


}

can anyone tell me what I am doing wrong because from my perspective nothing is wrong with the code. 谁能告诉我我在做什么错,因为从我的角度来看,代码没有错。 Thank You! 谢谢!

You mean like this: 您的意思是这样的:

public RustyChain() {
    super(8.0f);
}

weight = 8.0f doesn't call the super class constructor. weight = 8.0f不会调用超类构造函数。

The first default statement of a concrete class constructor is super(); 具体的类构造函数的第一个默认语句是super(); calling statement. 调用语句。

So, to make it work, you either remove 因此,要使其正常运行,您要么删除

public RustyChain()
{
 weight = 8.0f;
}

or add a no-arg constructor in the super class like this 或像这样在超类中添加无参数构造函数

public SunkenObject()
{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM