如何在 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

更新日期: 2019-10-14

4 千次觀看

開啟你的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.