Java 使用getName方法
包括以下内容: 返回学生对象名字的方法getFirstName 返回学生对象姓氏的方法getLastName 打印学生名字的语句与从getFirstName方法返回的名字相同。 打印学生姓氏的语句包含从getLastName方法返回的您的姓氏。 这就是我到目前为止所做的:Java 使用getName方法,java,Java,包括以下内容: 返回学生对象名字的方法getFirstName 返回学生对象姓氏的方法getLastName 打印学生名字的语句与从getFirstName方法返回的名字相同。 打印学生姓氏的语句包含从getLastName方法返回的您的姓氏。 这就是我到目前为止所做的: public class Student { //the student's full name String FirstName; String LastName; /** * Cr
public class Student
{
//the student's full name
String FirstName;
String LastName;
/**
* Create a new student with a given name a
*/
public Student(String name)
{
FirstName = name;
LastName = name;
}
/**
* Return the first name of this student
*/
public String getFirstName()
{
return FirstName;
}
/**
* Return the last name of this student
*/
public String getLastName()
{
return LastName;
}
public static void main(String[] args)
{
//gives a name to the students
Student FirstName = new Student("Samantha");
Student LastName = new Student("Jones");
//each object calls the getName method
System.out.println("The students first name is: " +Student.getFirstName());
System.out.println("The students last name is: " +Student.getLastName());
}
}
您创建了一个新对象,但以后不使用它 您应该为lastname的学生构造函数添加第二个参数:
public Student(String firstname, String lastname)
{
FirstName = firstname;
LastName = lastname;
}
主要是在创建后使用学生对象
public static void main(String[] args)
{
//gives a name to the students
Student stud1 = new Student("Samantha", "Jones");
Student stud2 = new Student("Timo", "Hantee");
//each object calls the getName method
System.out.println("The students first name is: " + stud1.getFirstName());
System.out.println("The students last name is: " + stud2.getLastName());
}
替换为:
public Student(String _firstname, String _lastname)//constructor header
{
FirstName = _firstname;//description of constructors
LastName = _lastname;
}
在学生类中,FirstName和LastName是两个不同的变量,因此需要在构造函数中为其指定不同的值。因此,与其用一个参数创建构造函数,不如用两个参数创建它,一个用于firstName,另一个用于lastName。如下图所示:
public Student(String firstName, String lastName)//constructor header
{
this.firstName = firstName;//description of constructors
this.lastName = lastName;
}
public static void main(String[] args)
{
//gives a name to the students
Student student= new Student("Samantha", "Jones");
//each object calls the getName method
System.out.println("The students first name is: " +student.getFirstName());
System.out.println("The students last name is: " +student.getLastName());
}
在这里,我想向您建议另外一件事,这对java程序员来说非常重要,遵循java命名约定。变量名应该以小写字母开头。如果你想有一个名字和一个姓氏,你的构造函数应该有两个字符串参数。我花了一个小时的时间才弄清楚。它现在正在工作: