Try   HackMD

進階Java筆記0311 Enum & Interface


抽象類別enum

就是個列舉式的抽象類別。以下的範例當中Monday、Tuesday等等,都是屬於類別。

public enum Week{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

enum使用方式

public class test { public enum Week {Mondat, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} public static void main(String [] args) { Week[] days = Week.values(); for(Week day: Week.values()) System.out.println(day + "(" + day.ordinal() + ")"); } }

enum特性

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

A. 可實作介面
C. 是安全型態
E. 可宣告private建構子 (無宣告預設為private)
F. 隱性(?)實作Comparable類別


What is typesafe in 爪哇?

一個避免 typeerror 的寫作方式。目的是要提前預測型別錯誤導致的當機。
如果程式執行中能夠被檢測出該程式的執行過程違背程式員的意圖,就該被標上「不安全」。


介面 (Interface)

  • 不可宣告變數 必須為常數 (final)
  • method預設為abstract 不可定義
  • Interface不可Instance (new)
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

    一個沒有被實做出來的類別無法被new。 ex: abstract

  • 可以一次Implements多個Interface
  • 一個class implements一個interface必須定義所有method

抽象類別 vs 介面(interface)

1. 整合需求

抽象類別 介面
整合同類 整合異類

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

2.語法

類別 介面
extends (擴充) implement (實作)

不要把負擔帶回家

public enum MyColor{ RED(0xff0000),GREEN(0x00ff00),BLUE(0x0000ff); private final int rgb; //field MyColor(int rgb){this.rgb = rgb;} public int getRGB(){return rgb;} } public static void main(String[] args){ MyColor purple = MyColor.GREEN;

卡蚯蚓烤肉

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

yogo osu

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →