用参数调用的Java构造函数

时间:2015-10-06 16:21:52

标签: java constructor compiler-errors

我试图用Student.java中的一个构造函数调用两个参数,如下所示:

public class InheritanceDemo {

public static void main(String[] args) {
    Student s = new Student(String SSname, int SSStudentID);}
    s.writeOutput();
}

Student.java

public class Student extends Person{
    public Student(String Sname, int SStudentID) {
        super(Sname);
        StudentID = SStudentID;
    }

    public void writeOutput() {
        System.out.println("Name:" + getName());
        System.out.println("StudentNumber:" + StudentID);
    }

Person.java

public Person() {
    name = "No name yet";       
} 
public Person (String initialName) {
    name = initialName;
}
public String getName() {
    return name;
}

这里Person.java是基类,Student.java是子类。我被显示以下错误:

Multiple markers at this line (near `Student s = new Student(String SSname, int SSStudentID);`
    - Syntax error on token "int", delete this 
     token
    - SSStudentID cannot be resolved to a 
     variable
    - String cannot be resolved to a variable
    - Syntax error on token "SSname", delete 
     this token

如何解决此问题?

2 个答案:

答案 0 :(得分:2)

调用方法(或构造函数)时,应传递实际值或变量:

更改:

Student s = new Student(String SSname, int SSStudentID);

类似于:

Student s = new Student("SomeName", 1234);

除此之外,我没有在您发布的代码中看到您声明StudentIDname成员变量的位置。

您的Student课程应该(除了当前内容):

public class Student extends Person { 
    private int StudentID;
}

您的Person课程应该(除了当前内容):

public class Person {
    private String name;
}

答案 1 :(得分:0)

main函数中存在语法错误您需要在调用构造函数之外声明变量SSname and SStudentID

执行以下操作

public static void main(String[] args)
{ Student s = new Student(String SSname, int SSStudentID);}
s.writeOutput();
}

public static void main(String[] args)
{ 
String SSname = "your_name";
int SSStudentID=10;
Student s = new Student(SSname,SSStudentID );}
s.writeOutput();
}

你的错误会消退