owned this note
owned this note
Published
Linked with GitHub
# 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

## 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. 
- ==**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.