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 5 ## Java: Casting - ==**Casting**== is the action of **converting from one type to another**. You can use the ``(newType)`` syntax to cast a value to a type named `newType`. - When you cast a primitive value to another type, there **may be a loss of precision**. ```java= double d = 5.3; System.out.println("Before casting to an int: " + d); int i = (int)d; // cast d to an int System.out.println("After casting to an int: " + i); d = (double)i; // cast i back to a double System.out.println("After casting back a double: " + d); ``` -> ```java= Before casting to an int: 5.3 After casting to an int: 5 After casting back a double: 5.0 ``` - ==**Downcasting**== is when you cast an object reference **from a superclass to a subclass**. - ==**Upcasting**== is when you cast an object reference **from a subclass to a superclass**. However, upcasting is done automatically by the compiler even if you do not specify it explicitly. - Note that due to **polymorphism**, the **behavior of the object will reflect the actual type of the object** irrespective of the type of the variable holding a reference to it. - Casting to an incompatible type can result in a **ClassCastException** at runtime. - You can use the **instanceof** operator to check if a cast is safe to perform. ```java= Cat c; if (a instanceof Cat){ c = (Cat)a; } ``` ## OOP + Java: Abstract Classes - ==**Abstract Class**==: A class declared as an abstract class **cannot be instantiated (實例化), but it can be subclassed**. - **You can declare a class as abstract when a class is merely a representation of commonalities among its subclasses** in which case it does not make sense to instantiate objects of that class. - ==**Abstract Method**==: An abstract method is a method signature **without a method implementation**. - **A class that has an abstract method becomes an abstract class** because the class definition is incomplete (due to the missing method body) and it is not possible to create objects using an incomplete class definition. - an abstract method is declared with the keyword **`abstract`** and given without an implementation. - In Java, **even a class that does not have any abstract methods can be declared as an abstract class.** - **When an abstract class is subclassed, the subclass should provides implementations for *all of the abstract methods* in its superclass or else the subclass must also be declared abstract.** - Choose the correct statements about Java abstract classes and concrete classes. - [ ] A concrete class can contain an abstract method. - [x] An abstract class can contain concrete methods. - [x] An abstract class need not contain any concrete methods. - [x] An abstract class cannot be instantiated. ## OOP + Java: Interfaces - An ==***interface***== is a **behavior specification** i.e. a collection of method specifications Just the method signature without any implementation. If a class implements the interface, it means the class is able to support the behaviors specified by the said interface. - **A class implementing an interface results in an** ***is-a relationship***, just like in class inheritance. - In Java, an interface is a reference type, similar to a class, **mainly containing method signatures**. - **Interfaces cannot be instantiated—they can only be implemented by classes.** When an instantiable class implements an interface, indicated by the keyword **`implements`**, it provides a method body for each of the methods declared in the interface. - **Interfaces can inherit from other interfaces using the `extends` keyword**, similar to a class inheriting another. - **Java allows multiple inheritance among interfaces. A Java interface can inherit multiple other interfaces. A Java class can implement multiple interfaces (and inherit from one class).** - Interfaces can also contain constants and static methods. ## Java: Packages - You can **organize your types (i.e., classes, interfaces, enumerations, etc.) into packages for easier management**. - **To create a package, you put a package statement at the very top of every source file in that package.** The package statement must be the first line in the source file and there can be no more than one package statement in each source file. Furthermore, **the package of a type should match the folder path of the source file.** Similarly, the compiler will put the `.class` files in a folder structure that matches the package names. - ex. The Formatter class below (in <source folder>/seedu/tojava/util/Formatter.java file) is in the package `seedu.tojava.util`. When it is compiled, the `Formatter.class` file will be in the location <compiler output folder>/seedu/tojava/util: ```java= package seedu.tojava.util; ``` - Package names are written in **all lower case** (not camelCase), using the dot as a separator. Packages in the Java language itself begin with java. or javax. Companies use their reversed Internet domain name to begin their package names. ```java= package seedu.tojava; import seedu.tojava.util.StringParser; import seedu.tojava.frontend.*; public class Main { public static void main(String[] args) { // Using the fully qualified name to access the Processor class String status = seedu.tojava.logic.Processor.getStatus(); // Using the StringParser previously imported StringParser sp = new StringParser(); // Using classes from the tojava.frontend package Ui ui = new Ui(); Message m = new Message(); } } ``` - **Importing a package does not import its sub-packages, as packages do not behave as hierarchies despite appearances.** ``` import seedu.tojava.frontend.* does not import the classes in the sub-package seedu.tojava.frontend.widget. ``` - Optionally, a **static import can be used to import static members of a type so that the imported members can be used without specifying the type name.** ## Java: Access Modifiers - At the **==class==** level: **public**: the class is visible to all classes everywhere **no modifier** (the default, also known as package-private): it is visible only within its own package - At the ==**member**== level: **public or no modifier** (package-private): same meaning as when used with top-level classes **private**: the member can only be accessed in its own class **protected**: the member can only be accessed within its own package (as with package-private) and, in addition, by a **subclass** of its class in another package ![](https://i.imgur.com/O6HAxCz.png =60%x) ## Error Handling: Exceptions - **Exceptions** are used to **deal with 'unusual' but not entirely unexpected situations** that the program might encounter at run time. - Most languages allow code that encountered an "exceptional" situation to **encapsulate details of the situation in an Exception object and throw/raise that object so that another piece of code can catch it and deal with it**. This is especially useful when the code that encountered the unusual situation does not know how to deal with it. - Three basic categories of exceptions In Java: 1. ==**Checked exceptions**==: exceptional conditions that a well-written application **should anticipate and recover from**. All exceptions are checked exceptions, except for Error, RuntimeException, and their subclasses. 2. ==**Errors**==: exceptional conditions that are **external to the application**, and that the application **usually cannot anticipate or recover from**. Errors are those exceptions indicated by Error and its subclasses. 3. ==**Runtime exceptions**==: conditions that are **internal to the application**, and that the application **usually cannot anticipate or recover from**. Runtime exceptions are those indicated by RuntimeException and its subclasses. These **usually indicate programming bugs, such as logic errors or improper use of an API.** - A program can catch exceptions by using a combination of the **`try`, `catch` blocks**. The try block identifies a block of code in which an **exception can occur**. The catch block identifies a block of code, known as an **exception handler**, that can handle a particular type of exception. - You can use a **`finally` block to specify code that is guaranteed to execute with or without the exception**. This is the right place to close files, recover resources, and otherwise clean up after the code enclosed in the try block. ```java= public void writeList() { print("starting method"); try { print("starting process"); process(); print("finishing process"); } catch (IndexOutOfBoundsException e) { print("caught IOOBE"); } catch (IOException e) { print("caught IOE"); } finally { // clean up print("cleaning up"); } print("finishing method"); } ``` - use the **`throw`** statement to throw an exception. The throw statement requires a throwable object as the argument. ```java= if (size == 0) { throw new EmptyStackException(); } ``` ## RCS: Branching, Pull Requests - ==**Branching**== is the process of **evolving multiple versions of the software in parallel.** - **A branch can be ==*merged*== into another branch.** Merging usually result in a new commit that represents the changes done in the branch being merged. ![](https://i.imgur.com/bQVIYcv.png =70%x) - ==**Merge conflicts**== happen when you try to **merge two branches that had changed the same part of the code** and the RCS software cannot decide which changes to keep. In those cases we have to ‘resolve’ those conflicts manually.

    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