我试图用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
如何解决此问题?
答案 0 :(得分:2)
调用方法(或构造函数)时,应传递实际值或变量:
更改:
Student s = new Student(String SSname, int SSStudentID);
类似于:
Student s = new Student("SomeName", 1234);
除此之外,我没有在您发布的代码中看到您声明StudentID
和name
成员变量的位置。
您的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();
}
你的错误会消退