返回列表 發帖

static 關鍵字 (一)

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

  1. public class Ch62
  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.         d1.showProfile();
  8.         d2.showProfile();
  9.         Cat c1=new Cat("咪咪",3,3.2);
  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 n, int a, double w)
  21.     {
  22.         sum++;
  23.         name=n;
  24.         age=a;
  25.         this.w=w;
  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 n, int a, double w)
  39.     {
  40.         sum++;
  41.         name=n;
  42.         age=a;
  43.         this.w=w;
  44.     }
  45.     void showProfile()
  46.     {
  47.         System.out.println(name+"今年"+age+"歲,體重"+w+"公斤.");
  48.     }
  49. }
複製代碼

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

返回列表