2013年12月21日

Java: protected 關鍵字

在開發java專案的時候常常會遇到某個方法或成員想被其他物件繼承,

但是又不想公開給大家使用,這時候就可以用 protected 關鍵字 來宣告。

例子如下:

Math.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package com.victorhsiao.blog.classes;

public class Math {

 public Math() {
 }

 public int Add(int n1, int n2) {
  return n1 + n2;
 }

 protected int Multiply(int n1, int n2) {
  return n1 * n2;
 }
}

main.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.victorhsiao.blog.classes;

public class main {
 private Math m = null;

 public int Quartic(int num) {
  m = new Math();
  return m.Multiply(num, num) * m.Multiply(num, num);
 }

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  main mm = new main();
  System.out.println(mm.Quartic(10));
 }

}

other.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.victorhsiao.blog.otherclasses;

import com.victorhsiao.blog.classes.Math;

public class other {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Math test = new Math();
  test.Multiply(10, 20); // error
 }
}

由於 Math 這個 class內的 Multiply 方法使用 protected,這使的

在套件 com.victorhsiao.blog.classes 下的物件都可存取它,
 
但是不同套件的物件卻看不到 (other.java)。 
 
當你有個方法想被繼承但又不想讓全世界都可存取,
 
這時棄用 public 改用 protected.
 
好的準則是: 將資料成員宣告為 private, 保留更動底層實作的權限,
 
透過protected method 來控制繼承者對你所撰寫的方法之存取權。 
 
 
 
Victor   2013/12/21 筆記  

沒有留言:

張貼留言