2013年5月10日 星期五

[Java] 認真的讀一次 Java Class 做個 Note


Creating A Class 

Class : Class definition and Class body

public/abstract/final  class  (NameOfClass) extends (Super) implements (Interface01, Interface02, ...) {
                         Class Body
}

public : 可以被任何 class 使用。沒有 public 只能給同一個 package 的使用
abstract :  宣告無法被 instantiated 的 class
final : 宣告無法被繼承的 class

Variable :  可以宣告的項目

accessLevel  (static/final/transient/volatile ) type name
    accessLevel :  宣告可以可 access memeber varialbe 的種類(public/protected/package/private)
   static : class variable 而不是 instance variable
   final : variable 的值無法改變
   transient: variable 不應該被 serialized
   volatile : 防止 compiler 對一個 member 進行某種最佳化
   type nmae : variable type and name




Class Method : 

AccessLevel  (static/abstract/fina;/native/synchronized)  ReturnType MethodName(Arguments) throws Exceptions{
                            Method Body
}
   accesslevel : 甚麼 class 可以 access method . (public/protected/package/private)
   static: a class method  rather than as an instance method
   abstract: Abstract method 沒有 implementation 而且必須是 abstract class 的 member
   final :  final method 無法被 subclasses overridden
   native : 如果呼叫 native 方法。  Native 是指用其他語言寫的(ie, C)
   synchronized: Thread-safe purposes for Concurrently running Threads

Naming Convention: 

    toString - 第一個字Lowercase 後面Uppercase

Name Overloading: 

   public void draw(String s);
   public void draw(int i);
   public void draw(float f);

Constructor : 

 public/private Stack() { (no return type)
}
     modifier:
     private : 只有這個class 可以呼叫這個 constructor。 當所有的 constructor 都沒private 時, 這個 class 可能有一個 public 的 class 來 initialize 一個 instance。(這個方法叫 factory method) 其它 class 可以使用 facotry method 來實現這個 class
   protected : subclass 跟 package 可以使用這個constructor
   public : 任何 class 都可以使用
  沒有 modifier : 只有這個 package 可以使用

Argument :  

Pass-by-value
public void getRGBColor(int r, int g , int b) 
這是 pass-by-value , 無法改變 r,g,b 原來的值
Pass-by-reference
但如果變成
public void getRGBColor(RGBColor aColor) 
因為是 pass aColor 這個 object 的 reference 就可以利用 acolor 的 setmethod 改變值


Return Type: 

return a value  : return 值 (ie:boolean, int etc.)
return a reference : return 一個 object 。 這個 Object 必須是其宣告類別或子類別


選擇 Access Levle 的 tip 

1. member 的話要用最嚴格的 - 最好是用 private
2. 除了 static 外少用 public memeber variable
3. 減少 protected 跟 package variables
4. 假如一個member variable 是 JavaBean 類別, 它必須是 private


Instance and Class Member 

每一個 instance 被 create 時都擁有自己的一個 instance member variable, 但卻會同時指向同一個 class member variable
int instantanceV1 = 1;
static int  classV1 =9;
Obj01.instatanceV1 跟 Obj02.instanceV2 不是同一個。但Obj01.classV1 跟 Obj02.classV2是同一個。

Initialize Instance and Class Member 

雖然在一開始時使用 assignment 就可以 initialize 但這有個限制是無法做 if else 等處理, 或是處理Exception。 所以多用在 primitive type 。 

這時如果要 initialize class memeber可以使用 Static Initialize Block 來解決問題。 
事實上 static 的 member 也不宜在 constructor 被 initialized
Class Errors { 
     static ResourceBundle errorStrings; 
     static { 
              try{
                        errorStrings = ResourceBundle.getBundle("errorString");
           }catch (java.util.MissResourceException e) {
                      //error recovery methods
          }
     }
}

這時如果要 initialize instance memeber可以在 constructor 宣告。 

Managing Inheritance 

SubClass 繼承 SuperClass 的所有方法與變數。但是 subClass 卻無法 access 所有superclass 的variables or methods。例如 Superclass 的 private memeber , subclass 就無法 access。還有 Constructor 不是 member 所以沒有被繼承


Override and hiding Method


  與superclass instance 有著相同的 signature 與 return type 的 subclass 的 instance memeber 叫做 Override method
    * can not override final method
    * must override abstract method
    * also can overloading

與superclass class member 有著相同的 signature 與 return type 的 subclass 的 class member 叫做  hidden  method。這個是有根本不同的。Runtime System, 會 invoke 被呼叫的method 的定義為 complie-time type 的reference。例如下例,myPlant 的 compile time type 是 Planet 所以呼叫的 method 是 planet 的 hide method。 可是 instance member 的 runtime type 是 Earth 所以, override 就被呼叫了。
(簡單的來說,static method 會被 hide, instant method 會被 override)
  Example: 

public class Planet { 
   public static void hide() {
                 System.out.println("The hide method is Planet");
   }
   public void override() {
                 System.out.println("The override method is Planet");
   }

public class Earth extends Planet { 
   public static void hide() {
                 System.out.println("The hide method is Earth");
   }
   public void override() {
                 System.out.println("The override method is Earth");
   }
    
   public void static main (String[] arg){
           Earth myearth = new Earth();
          Planet myplanet = (Planet) myearth; 
           myplanet.hide();
          myplanet.override();
      }

Result : 
The hide method is Planet
The override method is Earth


Hiding Member Variables 


subclass 裡跟 superclass 有相同名子的 variable(不一定要同type) hide superclass 的 variable。在 supclass 裡要使用 super class 的 member variable 不可以直接用名子,要使用 super()來access。


Super() 

*呼叫 method : super.method()
*呼叫 variable : super.variable
*呼叫 constructor : super();


Being a descendant of Object 


好用的 Object methods
     clone
     equals and hascode
     finalize
     toString
     getClass
    notify, notifyAll and wait


Writing Final Class and Method

為何要使用 final
    1. 安全: 很多hacker 會繼承 你的 classes來 hack system
    2. 好的 OOD design

Final class
      final class  classname {}
Final method : 也可以只宣布 final method。 當你的 method 很重要而且不應該被改變時,declare final
    final void methodname(){}

Writing Abstract Class and Method

Abstract Class
Present an abstract concept and should not be instantiate

abstract class ClassName ()

Abstract Methods
    * An abstract class can contain abstract methods (沒有 implementation 的 class)
    * 假如一個 abstract class 只有 abstract methods 那麼就 應該是要使用 Interface

Implementing Nested Classes 

A nested class is a member of another class

(accesslevel) (abstract/final)  class EnclosingClass{
   ....
        class ANestedClass{    
          }
}
 *使用 Nested class 1.當 nested class 的存在在EnclosingClass 下才有意義 2. 或是需要依賴enclosingclass的 function 。 (例子:  text cursor 只有在 context of text component 下才有意義)

 * Nested Class 可以 access enclosing class 的所有 members。  s
  * static nested class 叫 a static nested class , non-static 叫 inner class
  * static nested class 無法 access enclosing class的 non-static member , 如果要 access 只能用 Object Reference 的方式
 * inner class 可以 access " object " 的 instance methods and variables。 Inner class 不可以有 static members

*  Nested Class 就跟字面上的意思一樣 : 一個class 的 code 在另一個class 的 code 裡。同樣的 inner class 也跟字面上一樣的意思 -  反映出在兩個classes 裡 objects 的關係。 但有趣的點並不是關係,而是轉個方向看 " inner class instance 只存在 enclosing class instance 之下"  在這狀況下, 它可以存取 enclosing class 的 instance method and variable

* accesslevel/abstract/final can be applied to modifier as a normal class











沒有留言:

張貼留言