super()不允许我使用参数调用super构造函数 [英] super() not letting me call the super constructor with parameters

查看:126
本文介绍了super()不允许我使用参数调用super构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用带有两个参数的超类的构造函数,所以我调用了super(arguments),但是编译器说:

I want to call the super class' constructor that takes two arguments, so I call super(arguments), but the compiler says:

类中的构造函数Person无法将Person应用于给定类型;
需要
:没有参数

找到:Java.lang.String,int

原因:实际和正式参数列表不同长度

"Constructor Person in class Person cannot be applied to given types;
required: no arguments
Found: Java.lang.String, int
reason: actual and formal argument lists differ in length"

我不知道为什么会这样。对super的调用是第一行。参数匹配(但由于某种原因而不适用于编译器)。有人知道怎么回事吗?

I have no clue why this is happening. The call to super is the first line. The arguments match (but not to the compiler for some reason). Does anyone know what's going on?

顺便说一句,我正在使用NetBeans。最新版本。

I'm using NetBeans, by the way. The latest version.

编辑:我卸载了NetBeans,安装了Eclipse,现在一切正常。我不知道,也永远不会知道,为什么NetBeans给我一个错误。谢谢大家的帮助。

I uninstalled NetBeans, installed Eclipse, and now everything works perfectly. I don't know, nor will I ever know, why NetBeans gave me an error. Thanks everyone for your help.

public class Person
 {
 private String name;
 private int age;


 public Person() { name = " "; age = 0; }
 public Person(String nm, int ag) { name = nm; age = ag; }
 }


 public class BaseballPlayer extends Person
  {
  private int homeruns;
  private double bat_avg;


  BaseballPlayer()
  {
  super();
  homeruns = 0;
  bat_avg = 0;
  }

  BaseballPlayer(String name, int age, int hr, double bavg)
  {
  super(name, age); // THIS CAUSES AN ERROR. I DON'T KNOW WHY
  homeruns = hr;
  bat_avg = bavg;
  }
 } 


推荐答案

btw ,恕我直言,这是一种更好的形式,可以这样做:

btw, IMHO it's better form, to do this:

public class Person
    ...
    public Person() { 
        this("", 0); // No-args constructor calls the arg'd version with default values
    }

    public Person(String nm, int ag) {
        name = nm;
        age = ag;
    }
    ...
}

这意味着一切顺利通过一个构造函数。如果必须在构造函数中添加任何内容,则只有一个地方可以更改。

This means everything goes through the one constructor. If you have to add anything into your constructor, you have only one place to do change.

这篇关于super()不允许我使用参数调用super构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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