繁体   English   中英

带参数的Java构造函数调用

[英]Java constructor calling with parameters

我正在尝试使用以下两个参数在Student.java中调用构造函数:

public class InheritanceDemo {

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

学生.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);
    }

人.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

我该如何解决?

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

变更:

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;
}

您的主要功能中存在语法错误。您需要在调用构造函数之外声明变量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();
}

您的错误将会消失

暂无
暂无

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

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