我到处寻找,但什么也没找到。假设我们有一个学生类(class),这个类(class)有两个变量:姓名和年级。我想将创建的对象的名称插入到数组中(只有数组,没有数组列表)。我怎样才能做到这一点?
public class Student {
String name;
int grade;
public Student(String name, int grade) {
this.name=name;
this.grade=grade;
}
public String toString()
{
return "name:"+this.name+"grade:"+this.grade;
}
}
public class Demo {
public static void main(String[]args)
{
Student s1=new Student("Jason",73);
Student s2=new Student("Ricky",64);
Student s3=new Student("Mark",53);
}
}
最佳答案
通过 getter 返回属性值始终是一个好习惯。在Student类中创建一个getter方法并访问它来获取名称
public class Student {
private String name;
private int grade;
public String getName() {
return name;
}
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String toString() {
return "name:" + this.name + "grade:" + this.grade;
}
}
public static void main(String[]args) {
Student s1 = new Student("Jason", 73);
Student s2 = new Student("Ricky", 64);
Student s3 = new Student("Mark", 53);
String[] names = {s1.getName(), s2.getName(), s3.getName()};
}
关于Java将对象的变量插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36092102/