将字符串作为构造函数参数传递并获取“类型的非法开始”

时间:2019-03-28 08:37:19

标签: java constructor

我最近开始学习Java中的继承,但是这里有点问题,我可以在子类的构造函数中将实际的单词作为String(而不是变量)放置吗?

我尝试将其设置为公共Profesori(String emri,int vitiLindjes,“ Ligjerate”,String thirrjaAkademike),但没有运气

public class Mesimdhenesi {
    private String emri;
    private int vitiLindjes;
    private String angazhimi;

    public Mesimdhenesi(String emri, int vitiLindjes, String angazhimi) {

        this.emri = emri;
        this.vitiLindjes = vitiLindjes;
        this.angazhimi = angazhimi;
    }
}

public class Profesori extends Mesimdhenesi {
    private String thirrjaAkademike;


    public Profesori(String emri, int vitiLindjes, "Ligjerate", String thirrjaAkademike) {

        super(emri,vitiLindjes);

        this.thirrjaAkademike = thirrjaAkademike;

    }
}

得到此错误: Profesori.java:6:错误:类型的非法启动         公共Profesori(String emri,int vitiLindjes,“ Ligjerate”,String thirrjaAkademike){

3 个答案:

答案 0 :(得分:2)

您不能在方法或构造函数的定义中使用字符串文字。
如果要将字符串“ Ligjerate"作为super()构造函数的参数传递,则Profesori构造函数应类似于:

public Profesori(String emri, int vitiLindjes, String thirrjaAkademike) {

        super(emri,vitiLindjes, "Ligjerate");

        this.thirrjaAkademike = thirrjaAkademike;

    }

答案 1 :(得分:1)

我想你想要

public Profesori(String emri, int vitiLindjes, String thirrjaAkademike) {

    super(emri, vitiLindjes, "Ligjerate");

    this.thirrjaAkademike = thirrjaAkademike;

}

答案 2 :(得分:0)

这个想法没那么错,您只是将其放在代码的错误部分。 改变这个

public class Profesori extends Mesimdhenesi {
    private String thirrjaAkademike;


    public Profesori(String emri, int vitiLindjes, "Ligjerate", String thirrjaAkademike) {

        super(emri,vitiLindjes);

        this.thirrjaAkademike = thirrjaAkademike;

    }
}

对此:

public class Profesori extends Mesimdhenesi {
    private String thirrjaAkademike;


    public Profesori(String emri, int vitiLindjes, String thirrjaAkademike) {

        super(emri,vitiLindjes, "Ligjerate");

        this.thirrjaAkademike = thirrjaAkademike;

    }
}

您将实际单词传递给超级构造函数。

您的代码中有2个问题:

  1. 您的超级构造函数没有足够的参数(您需要3个,但您只给出了2个)

  2. 构造函数中的实际单词作为参数