Java 入門指南 V2.00 - 單元 10 範例




ClassDemo04.java


public class ClassDemo04 {
   private int a;

   // 這裡定義建構子
   public ClassDemo04(int p1) {
       setA(p1);
   }

   public void setA(int p1) {
      a = p1;
   }

   public int getA() {
      return a;
   }

   public int doSomething(int p1) {
      return a + p1;
   }

   public static void main(String[] args) { 
      ClassDemo04 d = new ClassDemo04(10);

      System.out.println();
      System.out.println(d.getA());
      System.out.println(d.doSomething(1));
      System.out.println();
   }
}
 
/* 檔名: ClassDemo04.java
   作者: Kaiching Chang
   時間: September, 2014  */

ClassDemo05.java


public class ClassDemo05 {
   private int a;

   public ClassDemo05(int a) {
       setA(a);
   }

   public void setA(int a) {
      // 利用 this 存取屬性
      this.a = a;
   }

   public int getA() {
      return a;
   }

   public int doSomething(int a) {
      // 參數跟屬性使用相同的識別字
      return this.a + a;
   }

   public static void main(String[] args) { 
      ClassDemo05 d = new ClassDemo05(13);

      System.out.println();
      System.out.println(d.getA());
      System.out.println(d.doSomething(9));
      System.out.println();
   }
}
 
/* 檔名: ClassDemo05.java
   作者: Kaiching Chang
   時間: September, 2014  */

the end

沒有留言: