Kate Lo
    • 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
    # Week 3 ## OOP: Classes and Objects * **OOP is a programming paradigm**. A programming paradigm guides programmers to analyze programming problems, and structure programming solutions, in a specific way. | Paradigm | Programming Languages | | -------- | -------- | | Procedural Programming paradigm | C | | Functional Programming paradigm | F#, Haskel, Scala| | Logic Programming paradigm | Prolog | * Java is primarily an OOP language but it supports limited forms of **functional programming** and it can be used to (although not recommended) write **procedural** code. * Choose the correct statements - [x] OO is a programming paradigm - [x] OO guides us in how to structure the solution - [x] OO is mainly an abstraction mechanism - [ ] OO is a programming language - [x] OO is modeled after how the objects in real world work * Choose the correct statements - [x] Java and C++ are OO languages - [ ] C language follows the Functional Programming paradigm - [x] Java can be used to write procedural code - [x] Prolog follows the Logic Programming * OOP views the world as a **network of interacting objects**. * OOP solutions try to **create a similar object network inside the computer’s memory** – a sort of a virtual simulation of the corresponding real world scenario – so that a similar result can be achieved programmatically. * **Every object has both state (data) and behavior (operations on data).** * Every object has an **interface** and an **implementation**. * **A ==class== contains instructions for creating a specific kind of objects.** It turns out sometimes multiple objects keep the same type of data and have the same behavior because they are of the same kind. * **==Objects==** in OOP is an abstraction mechanism because it allows us to **abstract away the lower level details and work with bigger granularity entities** * An object is an **==encapsulation==** of some data and related behavior in terms of two aspects: 1. The **packaging** aspect: An object packages data and related behavior together into one self-contained unit. 2. The **information hiding** aspect: The data in an object is hidden from the outside world and are only accessible using the object's interface. ## Java: Objects * `System` belongs to the **java.lang** package, which is imported automatically. * To create a new object, you have to use the `new` operator. * Variables that belong to an object are called **attributes (or fields)**. * In an example, the variable spot is assigned a `null` value. As a result, trying to access spot.x attribute or invoking the spot.translate method results in a `NullPointerException`. * It is possible to have **multiple variables that refer to the same object**. * **When an object is passed into a method as an argument, the method gains access to the original object.** * **==Garbage Collection==**: no variables refer to an object. In Java, you **don’t have to delete** objects you create when they are no longer needed. As your program runs, the **system automatically looks for stranded objects and reclaims them**; then the space can be reused for new objects. ## Java: Classes * The `this` keyword is a reference variable in Java that **refers to the current object**. * **`this` can be used to refer to a constructor of a class within the same class too.** ```java= public Time() { this(0, 0, 0); // call the overloaded constructor } public Time(int hour, int minute, int second) { // ... } ``` ## OOP, Java: Class-Level Members * **variables whose value is shared by all instances of a class are called ==class-level attributes==.** * **methods that are called using the class instead of a specific instance are called ==class-level methods==.** * Class-level attributes and methods are collectively called ==class-level members==. They are to be **accessed using the class name** rather than an instance of the class. * Sometimes, you want to have **variables that are common to all objects**. This is accomplished with the **`static`** modifier. * The **`static`** modifier, in combination with the **`final`** modifier, is also used to **define constants**. * Explanation of `System.out.println(...)`: `out` is a **class-level** public attribute of the System class. `println` is a **instance level** method of the out object. ## Java: Useful Classes * An Application Programming Interface (**API**) **specifies the interface through which other programs can interact with a software component**. It is a contract between the component and its clients. * When developing large systems, if you define the API of each components early, the development team can develop the components in parallel because the future behavior of the other components are now more predictable. * Choose the correct statements - [x] A software component can have an API. - [ ] Any method of a class is part of its API. - [x] Private methods of a class are not part of its API. - [x] The API forms the contract between the component developer and the component user. - [x] Sequence diagrams can be used to show how components interact with each other via APIs. ### The `String` class * **Find characters of a string**: **`charAt`** **returns a char**, a primitive type that stores an individual character (as opposed to strings of them). * **convert a string to an array of characters**: **`toCharArray`** ```java= char[] fruitChars = fruit.toCharArray() ``` * **Change a string to upper/lower case**: **`toUpperCase` / `toLowerCase`** a string method cannot change the string object on which the method is invoked, because **strings are immutable**. invoking the method has no effect if you don’t assign the return value to a variable. ```java= String s = "Ada"; s.toUpperCase(); // no effect s = s.toUpperCase(); // the correct way ``` * **Replacing parts of a string**: **`replace`** ```java= String text = "Computer Science is fun!"; text = text.replace("Computer Science", "CS"); System.out.println(text); -> CS is fun! ``` * **Accessing substrings**: **`substring`** "banana".substring(0) -> "banana" "banana".substring(2) -> "nana" "banana".substring(6) -> "" "banana".substring(0, 3) -> "ban" "banana".substring(2, 5) -> "nan" "banana".substring(6, 6) -> "" * **Searching within strings: `indexOf`** "banana".indexOf('a') -> 1 "banana".indexOf('a', 2) -> 3 searches for 'a', starting from position 2 "banana".indexOf('x') -> -1 "banana".indexOf("nan") -> 2 searches for the substring "nan" * **Comparing Strings: `equals` `compareTo` `equalsIgnoreCase`** If the strings differ, you can use **`compareTo`** to see **which comes first in alphabetical order**. The return value from compareTo is the difference between the first characters in the strings that differ.If the strings are equal, their difference is zero. **If the first string comes first in the alphabet, the difference is negative.** Otherwise, the difference is positive. **The uppercase letters come before the lowercase letters**, so "Ada" comes before "ada". To check **if two strings are similar irrespective of the differences in case**, you can use the **`equalsIgnoreCase`** method. * Others: `contains`: checks if one string is a sub-string of the other e.g., Snapple and app `startsWith`: checks if one string has the other as a substring at the beginning e.g., Apple and App `endsWith`: checks if one string has the other as a substring at the end e.g., Crab and ab * **Wrapper classes provide methods for parsing strings to other types**. ex. Integer.parseInt("1234") -> 1234 * **Wrapper classes also provide toString**, which returns a string representation of a value. ex. Integer.toString(1234) -> "1234" ### The `Arrays` class ```java= import java.util.Arrays ``` ```java= int[] a = new int[]{1,2,3,4}; int[] b = Arrays.copyOf(a, 3); // copy first three elements System.out.println(Arrays.toString(b)); int[] c = Arrays.copyOf(a, a.length); // copy all elements System.out.println(Arrays.toString(c)); -> [1, 2, 3] [1, 2, 3, 4] ``` ### The `Scanner` class ```java= import java.util.Scanner; ``` * `Scanner` is a class that provides methods for **inputting** words, numbers, and other data. * `nextLine` that reads a line of input from the keyboard and returns a String. ```java= public class Echo { public static void main(String[] args) { String line; Scanner in = new Scanner(System.in); System.out.print("Type something: "); line = in.nextLine(); System.out.println("You said: " + line); } } ``` ## Code Quality: Naming * Proper naming **improves the readability**. It also reduces bugs caused by ambiguities regarding the intent of a variable or a method. * **Use nouns for classes/variables and verbs for methods/functions.** * Avoid foreign language words, slang, and names that are only meaningful within specific contexts/times. * A name is not just for differentiation; it should explain the named entity to the reader accurately and at a sufficient level of detail. * If the name has multiple words, they should be in a sensible order. * Related things should be named similarly, while unrelated things should NOT. ## RCS: Using History * **RCS tools store the history of the working directory as a series of commits**. * To see what changed between two points of the history, you can ask the RCS tool to **diff** the two commits in concern. * To restore the state of the working directory at a point in the past, you can **checkout** the commit in concern. * You can use the git's **stash** feature to temporarily shelve (or stash) changes you've made to your working copy so that you can work on something else, and then come back and re-apply the stashed changes later on.

    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