我们如何在Java中的对象参数中初始化数组?
您可以使用构造函数或使用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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短