- OO特性:封裝、繼承、多型
- 高級特性:static, final, abstract, interface
- Class: 具有相同state和behavior的抽象集合
- Object: an instance of a class
Syntax
- method的parameter可省,但括號必須保留; method的實做可省
- member variable (in class) & local variable (in method), no global varaible
[modified] class class_name{
type attribute_name // member variable declaration
return_type method_name (parameters)[{method}] // method declaration
}
- 賦值或相等
- “=”: (primitive) assignment / (obj) reference to the same obj
- “==”: (primitive) equal / (obj) reference to the same obj?
- equals method
- Wrapper Class: equals () // the same value?
- Class: equals (==) // reference to the same obj?
- primitive: equals (x) // 不能使用method
- Initialization種類:
- constructor method: 沒有return_type,與class_name相同,new時才能使用
- default: 定義class時直接指定,固定
- lazy init (empty): setter/getter
- Initialization順序 (important):
- member variable // it can be used in all method(include constructor method)
- constrictor method
- general method在使用時才會初始化
- Method Overload: the same method_name, different parameters (e.g. multiple constructors)
- Object
- toString : override
- equals :
-
-
- primitive 跟 == 一樣
- obj
-
- casting:
- upcasting時,不可訪問子類新增加的成員屬性/方法
Animal a = new Cat(“Garfi”); // upcasting
-
- downcasting時(特化),需要強制轉型
- polymorphism/dynamic binding (execution time)
根據實際類型調用方法
-
- inherit
- override
- super reference to sub object
雷電範例
- abstract:
- 有abstract method,此class也必須定義為abstract
- 不能實體化
- final: 不能改變/重寫/繼承
- interface:
- 一種特殊的抽象類:
-
-
- 只有public final static常數 (不寫修飾也是)
- public方法定義(沒有實現)
-
-
- 一樣可以使用多型
- 可以實做多個介面
- 不同類可以實做單一介面
- 介面可以繼承介面