アットウィキロゴ

いろいろな修飾子

★いろいろな修飾子


final
フィールドは値の変更不可となり、クラスは継承不可となる
finalint = 3 ;        ←代入できなくなる
 
finalclass Animal {
}                        ←継承できなくなる
 
static
staticがついたフィールドは値が同一になる。
Class A {
staticint a;
}
A a1 = new A;
A a2 = new A;
 
al.a = 50;
 
 

※staticメソッドは非staticメソッドではオーバーライドできない
※staticメソッドから同じオブジェクト内のstaticであるメンバやメソッドを参照できる

■サンプルプログラム

class Purse {
   static int money = 0;
  
   void printMoney(int in, int out) {
      money = money + in - out;
      if(money < 0)
         System.out.println((-1 * money) + "円足りません。");
      else
         System.out.println("残高は" + money + "円です。");
   }
}

class Shopping {
   public static void main(String[] args){
      Purse store1 = new Purse();
      Purse store2 = new Purse();
      store1.printMoney(1000, 100);
      store2.printMoney(0, 250);
      store1.printMoney(0,800);
   }
}

■サンプルプログラム

class Drink {
   String name;  // 商品名
   int price;   // 単価
   int count;   // 数量

   // コンストラクタ
   Drink(String n, int p, int c){
      name = n;
      price = p;
      count = c;
   }
  
   int getTotalPrice(){ // 金額を計算
      return count * price;
   }

   static void printTitle(){
      System.out.println("商品名\t\t単価\t数量\t金額");
   }
  
   void printData() {
      System.out.println(name + "\t" + price + "\t" + count + "\t" + getTotalPrice());
   }
}

class Alcohol extends Drink {
   float alcper;   // アルコールの度数

   // コンストラクタ
   Alcohol(String n, int p, int c, float a){
      super(n, p, c); // スーパークラスのコンストラクタを呼び出す
      alcper = a;
   }
   // メソッドのオーバーライド
   static void printTitle() {
      System.out.println("商品名(度数[%])\t単価\t数量\t金額");
   }
   //メソッドのオーバーライド
   void printData() {
      System.out.println(name + "(" + alcper + ")" + "\t" + price + "\t" + count + "\t" + getTotalPrice());
   }
}

class Payment{
   public static void main(String[] args){
      Drink coffee = new Drink("コーヒー", 200, 3);
      Drink oolongtea = new Drink("ウーロン茶", 150, 2);
      Alcohol wine = new Alcohol("ワイン", 300, 2, 15.0f);

      Drink.printTitle();
      coffee.printData();
      oolongtea.printData();
      System.out.println();

      Alcohol.printTitle();
      wine.printData();
      int sum = coffee.getTotalPrice() + oolongtea.getTotalPrice() + wine.getTotalPrice();
      System.out.println("\n*** 合計金額" + sum + "円 ***");
   }
}

最終更新:2008年03月08日 12:21