这个构造函数引用在java中不起作用

问题描述 投票:0回答:1

我尝试应用 this() 方法来调用 java 中的相同构造函数,以尝试创建一个构造函数,我们只需提供名称和类,它将选择角色的参数,但它不起作用,我不熟悉使用此方法在java中。

type public class Jugador{
    //campos
    private String nombre;
    private String clase;
    private int vida;
    private int ad;
    private int ap;
    private int def;
    private int mr;

    //constructores
    private Jugador(String nombre, String clase, int vida, int ad, int ap, int def, int mr){
        this.nombre = nombre;
        if (clase.equals("hunter") || clase.equals("warrior") || clase.equals("assasin") || clase.equals("tank")){
            this.clase = clase;
        }
        else{
            this.clase = "normal";
        }
        this.vida = vida;
        this.ad = ad;
        this.ap = ap;
        this.def = def;
        this.mr = mr;
    }

    public Jugador(String nombre, String clase){
        if (clase.equals("hunter")){
            this(nombre, clase, 120, 50, 0, 40, 0);
        }
        else if (clase.equals("warrior")){
            this(nombre, clase, 100, 70, 0, 80, 0);
        }
        else if (clase.equals("assasin")){
            this(nombre, clase, 60, 120, 0, 20, 0);
        }
        else if (clase.equals("tank")){
            this(nombre, clase, 200, 20, 0, 80, 0);
        }
        else if(clase.equals("normal")){
            this(nombre, clase, 80, 80, 0, 80, 0);
        }
    }


    }here
java object this
1个回答
0
投票

Java 中没有

this
方法。
this
是一个关键字 - 请在此处阅读:https://www.w3schools.com/java/ref_keyword_this.asp

虽然问题并没有完全清楚你想要实现的目标 - 只需将 this(...) 替换为第一个构造函数:

public class Jugador{
  //campos
  private String nombre;
  private String clase;
  private int vida;
  private int ad;
  private int ap;
  private int def;
  private int mr;

  //constructores
  private Jugador(String nombre, String clase, int vida, int ad, int ap, int def, int mr){
    this.nombre = nombre;
    if (clase.equals("hunter") || clase.equals("warrior") || clase.equals("assasin") || clase.equals("tank")){
      this.clase = clase;
    }
    else{
      this.clase = "normal";
    }
    this.vida = vida;
    this.ad = ad;
    this.ap = ap;
    this.def = def;
    this.mr = mr;
  }

  public Jugador(String nombre, String clase){
    if (clase.equals("hunter")){
      new Jugador(nombre, clase, 120, 50, 0, 40, 0);
    }
    else if (clase.equals("warrior")){
      new Jugador(nombre, clase, 100, 70, 0, 80, 0);
    }
    else if (clase.equals("assasin")){
      new Jugador(nombre, clase, 60, 120, 0, 20, 0);
    }
    else if (clase.equals("tank")){
      new Jugador(nombre, clase, 200, 20, 0, 80, 0);
    }
    else if(clase.equals("normal")){
      new Jugador(nombre, clase, 80, 80, 0, 80, 0);
    }
  }


}

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.