JerryWang168
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 【韩顺平讲Java】Chapter7 - 面向对象编程(基础部分) *** > **即使再小的帆也能遠航** > 參考自[【零基础 快速学Java】韩顺平 零基础30天学会Java](https://www.bilibili.com/video/BV1fh411y7R8/?vd_source=c5074574112ef27dae243d70aa2175b8) >###### tags: `韓順平講Java` *** # 類與對象 - 類是一種**自定義** 的 **==數據類型==** - 對象是類的具體實例 ![](https://i.imgur.com/yGfHZKu.png) - 有過程的 (P199) ![](https://i.imgur.com/O4oF0ze.png) ![](https://i.imgur.com/SjMy7DZ.jpg) # 成員方法 ![](https://i.imgur.com/7Gl5mSt.jpg) - 訪問修飾符有四 : public, protected, private, (默認) ```java= package chapter7; public class MethodExercise01 { public static void main(String[] args) { AA a = new AA(); System.out.println(a.isOdd(2)); a.printTable(4, 4, '#'); } } class AA { public boolean isOdd (int num){ // return num % 2 == 0 ? false : true; return num % 2 != 0; } public void printTable(int row, int col, char chr){ for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { System.out.print(chr + "\t"); } System.out.println(); } } } ``` # 成員方法傳參機制 - 很多內存圖、理解 # 方法遞歸調用 ## 老鼠走迷宮 ```java= package chapter7; public class MiGong { public static void main(String[] args) { // 思路 // 1. 先創建迷宮,使用二維數組 // 2. 規定元素值 : 0 表示可以走,1表示障礙物 int[][] map =new int[8][7]; // 3. 外層設為1 for (int i = 0; i < 7; i++) { map[0][i] = 1; map[7][i] = 1; } for (int i = 1; i < 8; i++) { map[i][0] = 1; map[i][6] = 1; } // 4. 設置障礙物 map[3][1] = 1; map[3][2] = 1; map[2][2] = 1; // 輸出當前迷宮 System.out.println("====當前地圖===="); for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { System.out.print(map[i][j]+" "); } System.out.println(); } // 使用findWay給老鼠找路 T t1 = new T(); t1.findWay(map, 1, 1); // 輸出當前迷宮 System.out.println("====找路的情況如下===="); for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { System.out.print(map[i][j]+" "); } System.out.println(); } } } class T{ // 使用遞規回溯的思想來解決老鼠出迷宮 // 老韓解讀 // 1. findWay 就是專門來找出迷宮的路徑 // 2. 如果找到,返回true,否則false // 3. map 就是二維數組,即表示迷宮 // 4. (i,j)是老鼠的位置,初始位置是(1,1) // 5. 因為是遞歸的找路,所以得先規定map數值的含意 // 0 表示可以走,1表示障礙物,2表示可以走,3表示走過,但是走不通 // 6. 當map[6][5] = 2,就說明找到通路,可以退出,否則就繼續找 // 7. 先確定老鼠找路的策略 下 -> 右 -> 上 -> 左 public boolean findWay(int[][] map, int i, int j){ if (map[6][5] == 2){ // 說明已經找到 return true; } else { if (map[i][j] == 0) { // 當前這個位置0,表示可以走 // 我們假定可以走通 map[i][j] = 2; // 使用找路的策略,來確定該位置是否可以走通 // 下 -> 右 -> 上 -> 左 if (findWay(map, i + 1, j)){ return true; } else if (findWay(map, i, j + 1)){ return true; } else if (findWay(map, i - 1, j)){ return true; } else if (findWay(map, i, j - 1)){ return true; } else { map[i][j] = 3; return false; } } else { //map[i][j] == 1,2,3 return false; // 已經走過或走不通,不須再嘗試 } } } } ``` ## 漢諾塔 ```java= package chapter7; public class HanoiTower { public static void main(String[] args) { Tower tower = new Tower(); tower.move(64, 'A', 'B', 'C'); } } class Tower{ // num 表示要移動的個數 // a, b, c分別表示 初始, 過度, 目標塔 public void move(int num, char a, char b, char c){ // 如果只有一個盤 if (num == 1){ System.out.println(a + " -> " + c); }else{ // 如果有多個盤,可以看成兩個,最下面的和上面的所有盤(num-1) // (1) 先移動上面的所有盤到b,借助c move(num - 1, a, c, b); // (2) 把最下面的這個盤,移動到c System.out.println(a + " -> " + c); // (3) 再把b塔的所有盤,移動到c,借助a move(num-1, b, a, c); } } } ``` ## 八皇后 - 自己寫的 ```java= package chapter7; public class EightQueen { public static void main(String[] args) { int[] map = new int[8]; // int[] test = {0,4,7,5,2,6,1,3}; Solver solver = new Solver(); for (int i = 0; i < map.length; i++) { solver.solve(map, 0, i); } } } class Solver{ static int ways = 1; public void solve (int[] map, int row, int pos) { map[row] = pos; if (row == 7 && check(map,7)) { System.out.print("第"+ ways++ +"種方法: {"); for (int i = 0; i < map.length; i++) { System.out.print(map[i] + " "); } System.out.println("}"); } else { if (check(map, row)){ for (int i = 0; i < map.length; i++) { solve(map, row+1, i); } } } } /* * 檢查新加入(row)皇后對整個棋盤的影響,過去檢查的一定合格,無須重複確認 * 新加入的一定在最後,所以檢查到row就行 */ public boolean check(int[] map, int row) { // 檢查重複 for (int i = 0; i < row; i++) { if (map[i] == map[row]) { return false; } } // 向斜檢查 for (int i = 1; i <= row; i++) { if (map[row]+i == map[row - i] || map[row]-i == map[row - i]){ return false; } } return true; } } ``` # 重載 (overload) ![](https://i.imgur.com/iPdlJIN.png) # 可變參數 ![](https://i.imgur.com/YjIjP8n.png) ![](https://i.imgur.com/7Hkm3x7.jpg) # 作用域 ![](https://i.imgur.com/vU0k83h.jpg) ![](https://i.imgur.com/wrGOPuJ.jpg) ![](https://i.imgur.com/lWYQZUK.jpg) # 構造器 - 主要作用是完成對**新對象的初始化** ![](https://i.imgur.com/KReyVQp.jpg) - 可以使用javap反編譯.class文件 :::info javap Dog.class (.class可以不寫) ::: - P245 ![](https://i.imgur.com/osPPJkg.jpg) ![](https://i.imgur.com/DdBmKYD.png) # this ![](https://i.imgur.com/emUvt5B.png) ![](https://i.imgur.com/hqrEOR8.jpg) # 本章作業 ## 1 ![](https://i.imgur.com/pBrjh6f.png) ```java= package chapter7; public class Homework01 { public static void main(String[] args) { double[] arr = {1,2,3,4,5,6,7,8,9}; A01 a01 = new A01(); System.out.println(a01.max(arr)); } } class A01{ public double max (double[] arr) { double max = arr[0]; for (int i = 1; i < arr.length; i++) { if (max < arr[i]){ max = arr[i]; } } return max; } } ``` ## 2 ![](https://i.imgur.com/loHcNVw.png) ```java= package chapter7; public class Homework02 { public static void main(String[] args) { String[] arr = {"Jerry","Tome","Amy","Elsa"}; A02 a02 = new A02(); System.out.println(a02.find(arr, "Elsa")); } } class A02{ public int find(String[] arr, String findElm){ for (int i = 0; i < arr.length; i++) { if (findElm.equals(arr[i])){ return i; } } return -1; } } ``` ## 3 ![](https://i.imgur.com/kpxXOfR.png) ```java= class Book { private int price; public Book (){} public Book (int price){ this.price = price; } public void updatePrice (Book book){ if (book.price > 150){ book.price = 150; } else { book.price = 100; } } } ``` ## 4 ![](https://i.imgur.com/fRAEBWv.png) ```java= class A03 { public int[] copyArr (int[] arr){ int[] ret = new int[arr.length]; for (int i = 0; i < arr.length; i++){ ret[i] = arr[i]; } return ret; } } ``` ## 5 ![](https://i.imgur.com/FX3FXuj.png) ```java= package chapter7; public class Homework05 { public static void main(String[] args) { Circle circle = new Circle(2); circle.getArea(); circle.getPerimeter(); } } class Circle{ double radius; public Circle(double radius){ this.radius = radius; } public void getPerimeter (){ if (radius < 0) { System.out.println("無效半徑"); } else { System.out.println(2*Math.PI*radius); } } public void getArea (){ if (radius < 0) { System.out.println("無效半徑"); } else { System.out.println(Math.PI*radius*radius); } } } ``` ## 6 ![](https://i.imgur.com/jQlndEB.png) ```java= package chapter7; public class Homework06 { public static void main(String[] args) { Cale c1 = new Cale(2.5, 0.5); System.out.println(c1.sum()); System.out.println(c1.sub()); System.out.println(c1.time()); System.out.println(c1.div()); Cale c2 = new Cale(2.7, 0); System.out.println(c2.sum()); System.out.println(c2.sub()); System.out.println(c2.time()); System.out.println(c2.div()); } } class Cale { double d1; double d2; public Cale(double d1, double d2) { this.d1 = d1; this.d2 = d2; } public double sum (){ return d1 + d2; } public double sub (){ return d1 - d2; } public double time (){ return d1 * d2; } public Double div (){ if (d2 == 0){ System.out.println("無效除數"); return null; } else { return d1 / d2; } } } ``` ## 7 ![](https://i.imgur.com/Y07ZW9N.png) ```java= class Homework07{ public static main (String[] args){ Dog dog = new Dog("旺財","Yellow","10"); dog.show(); } } class Dog { String name; String color; int age; public Dog (String name, String color, int age){ this.name = name; this.color = color; this.age = age; } public void show(){ System.out.println("Dog name is "+ this.name); System.out.println("Dog color is "+ this.color); System.out.println("Dog age is "+ this.age); } } ``` ## 8 ![](https://i.imgur.com/UCV38ss.png) count1 = 10 count1 = 9 count1 = 10 ## 9 ![](https://i.imgur.com/Ug2poGe.png) ```java= class Music { String name; int times; public Music (String name, int times){ this.name = name; this.times = times; } public void play (){ System.out.println("音樂播放中...") } public void getInfo (){ System.out.println("音樂名為"+name); System.out.println("音樂時長 "+times+" sec"); } } ``` ## 10 ![](https://i.imgur.com/5jWR8X6.png) i=101 j=100 101 101 ## 11 ![](https://i.imgur.com/9PSYCjT.png) ```java public double method (double d1, double d2){...} ``` ## 12 ![](https://i.imgur.com/FKklW8Y.png) - 重點 : 如何**複用** ```java= class Employee { String name, position; char gen; int age, sal; /* public Employee (String name, char gen, int age, String position, int sal){ this.name = name; this.gen = gen; this.age = age; this.position = position; this.sal = sal; }*/ public Employee (String name, char gen, int age){ this.name = name; this.gen = gen; this.age = age; } public Employee (String position, int sal){ this.position = position; this.sal = sal; } public Employee (String name, char gen, int age, String position, int sal){ this(name, gen, age); // this(position, sal) // 想法是好的,但構造器一定要放在第一個,所以會報錯 this.position = position; this.sal = sal; } } ``` ## 13 ![](https://i.imgur.com/Wx6RyDb.jpg) ```java= package chapter7; public class Homework13 { public static void main(String[] args) { Circle2 circle = new Circle2(); PassObject passObject = new PassObject(); passObject.printAreas(circle, 5); } } class Circle2{ double radius; public double getArea (){ return Math.PI*radius*radius; } } class PassObject { public void printAreas(Circle2 c, int times){ System.out.println("Radius\tArea"); for (int i = 1; i <= times; i++) { c.radius = i; System.out.println((double)i+"\t"+c.getArea()); } } } ``` ## 14 ![](https://i.imgur.com/JKbNpEF.png) ```java= Random r = new Random(); r.nextInt(3); ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully