返回列表 發帖

static 關鍵字 (一)

本帖最後由 tonyh 於 2015-3-28 15:09 編輯

成員 (資料成員或方法成員) 在宣告時若使用關鍵字 static 修飾,則該成員變成屬於類別 (class) 擁有而非物件 (object) 擁有,因此我們若要在其他地方使用該成員時,不用建立實體物件,只需透過類別即可使用。譬如:Math.PI 即為靜態的資料成員,而Math.pow() 即為靜態的方法成員。

  1. public class ch64
  2. {
  3.     public static void main(String args[])
  4.     {
  5.         Dog d1=new Dog("憨憨",2,3.8);
  6.         Dog d2=new Dog("球球",1,2.5);
  7.         Cat c1=new Cat("咪咪",5,3.2);
  8.         d1.showProfile();
  9.         d2.showProfile();
  10.         c1.showProfile();
  11.         System.out.println("總共有"+Dog.sum+"隻狗,"+Cat.sum+"隻貓.");
  12.     }
  13. }
  14. class Dog
  15. {
  16.     static int sum=0;
  17.     String name;
  18.     int age;
  19.     double w;
  20.     Dog(String name, int age, double w)
  21.     {
  22.         this.name=name;
  23.         this.age=age;
  24.         this.w=w;
  25.         sum++;
  26.     }
  27.     void showProfile()
  28.     {
  29.         System.out.println(name+"今年"+age+"歲,體重"+w+"公斤.");
  30.     }
  31. }
  32. class Cat
  33. {
  34.     static int sum=0;
  35.     String name;
  36.     int age;
  37.     double w;
  38.     Cat(String name, int age, double w)
  39.     {
  40.         this.name=name;
  41.         this.age=age;
  42.         this.w=w;
  43.         sum++;
  44.     }
  45.     void showProfile()
  46.     {
  47.         System.out.println(name+"今年"+age+"歲,體重"+w+"公斤.");
  48.     }
  49. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

返回列表