Java将对象的变量插入数组

标签 java arrays object

我到处寻找,但什么也没找到。假设我们有一个学生类(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/

相关文章:

java - 以编程方式重启 Linux m/c

javascript - jQuery grep 返回多维数组

php - 如何检查类方法需要参数

javascript - 将两个数组组合成 JSON 中的一个对象

Java - 类中的重复方法以及如何从另一个类中调用它们

java - 当 RHS == Integer.MAX_VALUE 时对 int 进行 boolean 比较,为什么这个循环会终止?

java - 四色定理的递归算法

arrays - 获取数组的中位数

java - 字符串数组 - 唯一值的实例

c# - 在 C# 中,如果将列表中的对象添加到另一个列表中,更改第二个列表中的对象是否会更改第一个列表中的同一对象?