java - 带参数的Java构造函数调用

标签 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();
}

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

关于java - 带参数的Java构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32974881/

相关文章:

java - 如何从另一个调用一个空的构造函数?

java - 将构造函数参数传递给 JAVA 方法

c++ - 无法在 C++ 中使用 conio 库

variables - 代码的最后一部分中的错误与其余代码完全相同

java - Java中的JComboBox,声明错误

javascript - 在原型(prototype)上定义方法

java - 如何从 JFileChooser(JAVA Swing) 禁用文件操作、文件选择和过滤面板?

java - 具有多个值的 JPA 选择查询

java - 无法构建 apk - android studio

java - 无效的 keystore 格式 - tomcat