封裝與存取修飾詞

Java 物件導向程式設計入門

Sani Yusuf

Lead Software Engineering Content Developer

認識封裝

  • 可用行動裝置來說明封裝
  • 你只能使用對外公開的功能,如螢幕、喇叭等
  • 內部運作對使用者完全隱藏

手機

Java 物件導向程式設計入門

Public 屬性

  • 標記為 public 的屬性可由物件實例存取

  class Car {
    // Public property
    public String color;


// Public constructor public Car(String color){ this.color = color; } }

    public class Main {

      // main method
      public static void main(String[] args) {
          Car myCar = new Car("brown");
          // Can access public members 
          // from object instance
          System.out.println(
            myCar.color); // Brown
        }
      }

Java 物件導向程式設計入門

Private 屬性

  • 標記為 private 的屬性不可由物件實例存取
  • 標記為 private 的屬性僅能在類別內使用

  // Car class
  class Car {
     public String color;

// Private properties private String model;
public Car(String color){ this.color = color; } }

    // Main class
    public class Main {
      // main method
      public static void main(String[] args) {
          Car myCar = new Car("brown");
          // Calling private properties causes errors        
          System.out.println(
            myCar.model); // Java compilation error
        }
      }


Java 物件導向程式設計入門

Public 方法


  // Car class
  class Car {
      public String color;
      private String model;

      public Car(String color){
          this.color = color;
      }

      // Public method
      public String getModel(){
          return this.model;
      }    
  }    

Java 物件導向程式設計入門

Private 方法


  class Car {


// Private method, "calculateSpeed" can only be used within "Car" class private calculateSpeed(){ // Trademarked formula code } public int getSpeed(){ // "calculateSpeed" can be used anywhere within "Car" class return this.calculateSpeed(); } }
Java 物件導向程式設計入門

Static 方法

  • 標記為 static 的屬性可不需物件實例即可存取
  • 常用來放共用程式碼/函式庫

   // Formula class 
   static class Formula {

     // Method for calculating square
     static int getSquare(int number) {
        return number * number;
      }
   }





  // Main class 
  public class Main {

    public static void 
      main(String[] args) {
          // We can use "getSquare" 
          // without an object instance
        System.out.println(
          Formula.getSquare(5)); // 25
      }
  }

Java 物件導向程式設計入門

重點回顧

  • 存取修飾詞:publicprivatestatic
  • 存取修飾詞有助於強化應用程式安全
  • static 讓你可不建立實例就使用類別
Java 物件導向程式設計入門

一起來練習吧!

Java 物件導向程式設計入門

Preparing Video For Download...