Basic OO in Java

OO特性:封裝、繼承、多態
高級特性:static, final, abstract, interface
Class: 具有相同屬性和行為的抽象集合
Object: an instance of a class
[modified] class class_name{
type attribute_name // attribute
return_type method_name (parameters)[{method}] // method
}
parameter可省,但括號必須保留
method實做可省
Constructor method:對obj初始化
沒有return_type,與class_name相同,new時用
Local variable: in method
membership varaible: in class
  • 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種類:
  1. constructor method: 沒有return_type,與class_name相同,new時才能使用
  2. default: 定義class時直接指定,固定
  3. lazy init (empty): setter/getter
  • Initialization順序 (important):
  1. member variable // it can be used in all method(include constructor method)
  2. constrictor method
  3. general method在使用時才會初始化
  • Method Overload: the same method_name, different parameters (e.g. multiple constructors)
  • Object
    • toString : override
    • equals :
      1. primitive 跟 == 一樣
      2. obj
  • casting:
    • upcasting時,不可訪問子類新增加的成員屬性/方法

Animal a = new Cat(“Garfi”); // upcasting

    • downcasting時(特化),需要強制轉型
  • polymorphism/dynamic binding (execution time)

根據實際類型調用方法

    1. inherit
    2. override
    3. super reference to sub object

雷電範例

  • abstract:
    • 有abstract method,此class也必須定義為abstract
    • 不能實體化
  • final:  不能改變/重寫/繼承
  • interface:
    • 一種特殊的抽象類:
      1. 只有public final static常數 (不寫修飾也是)
      2. public方法定義(沒有實現)
    • 一樣可以使用多型
    • 可以實做多個介面
    • 不同類可以實做單一介面
    • 介面可以繼承介面
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.