【发布时间】:2019-05-06 06:49:43
【问题描述】:
我正在尝试在我的主类中实例化一个学生、研究生和 MBAstudent,并调用 setter 来设置他们的名字和姓氏,但我遇到了一个错误“Student 类型中的方法 setFirstName(String) 是不适用于论据(学生)"
我的主课如下:
public class Main {
public static void main(String[] args) {
Student bob = new Student();
GradStudent john = new GradStudent();
MBAstudent michael = new MBAstudent();
bob.setFirstName(bob);
bob.setLastName(smith);
bob.setmNumber(1);
bob.setMatriculated(true);
john.setFirstName(john);
john.setLastName(white);
john.setmNumber(2);
john.setMatriculated(true);
john.setAge(23);
michael.setFirstName(michael);
michael.setLastName(scott);
michael.setmNumber(3);
michael.setMatriculated(true);
michael.setGpa(4.0);
}
}
我的学生班级:
public class Student {
private String firstName;
private String lastName;
private int mNumber;
private boolean matriculated;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getmNumber() {
return mNumber;
}
public void setmNumber(int mNumber) {
this.mNumber = mNumber;
}
public boolean isMatriculated() {
return matriculated;
}
public void setMatriculated(boolean matriculated) {
this.matriculated = matriculated;
}
public String toString() {
return (firstName + " " + lastName + " has an MNumber of " +
mNumber + " and is enrolled");
}
我的研究生班:
public class GradStudent extends Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return (getFirstName() + " " + getLastName() + " has an MNumber of " +
getmNumber() + " and is " + age + " years old and is enrolled");
}
和我的 MBA 学生班:
public class MBAstudent extends Student {
private double gpa;
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public String toString() {
return (getFirstName() + " " + getLastName() + " has an MNumber of " +
getmNumber() + " and has a GPA of " + gpa + " years old and is enrolled");
}
【问题讨论】:
-
嗨!试试这个:
bob.setFirstName("bob");而不是 bob.setFirstName(bob);您在 Student 类中的代码public void setFirstName(String firstName)正在寻找 String 作为输入。当您发送bob时,您发送的是Student 类型的对象。当您发送"bob"时,您将发送一个字符串 - 这就是 Student 对象的setFirstName想要的。将 smith、john 等更改为带双引号的字符串,看看你的程序是如何工作的。 -
哇。多么简单的错误!非常感谢。
-
不客气。您在描述问题和代码方面做得非常出色!
标签: instantiation