如何在 Java 中初始化对象参数内的数组?
javaobject oriented programmingprogramming
您可以像其他任何值一样初始化在类内部声明的数组变量,可以使用构造函数或使用 setter 方法。
示例
在下面的 Java 示例中,我们声明一个数组类型的实例变量并从构造函数中初始化它。
public class Student { String name; int age; String subs[]; Student(String name, int age, String subs[]){ this.name = name; this.age = age; this.subs = subs; } public void display() { System.out.println("Name: "+this.name); System.out.println("Age :"+this.age); System.out.print("Subjects: "); for(int i = 0; i < subs.length; i++) { System.out.print(subs[i]+" "); } } public static void main(String args[]) { String subs[] = {"Mathematics", "English", "Science", "Social"}; Student obj = new Student("Krishna", 25, subs); obj.display(); } }
输出
Name: Krishna Age :25 Subjects: Mathematics English Science Social
示例2
public class Student { String name; int age; String subs[]; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setSubs(String[] subs) { this.subs = subs; } public void display() { System.out.println("Name: "+this.name); System.out.println("Age :"+this.age); System.out.print("Subjects: "); for(int i = 0; i < subs.length; i++) { System.out.print(subs[i]+" "); } } public static void main(String args[]) { String subs[] = {"Mathematics", "English", "Science", "Social"}; Student obj = new Student(); obj.setName("Krishna"); obj.setAge(25); obj.setSubs(subs); obj.display(); } }
输出
Name: Krishna Age :25 Subjects: Mathematics English Science Social