cs61b Note
JAVA Interface
Static Type and Dynamic Type
- Every variable has a “compile-time type” at declaration. a.k.a “Static type” and it cannot be changed.
- Every variable has a “run-time type” at instantiation a.k.a “Dynamic Type” and it can be changed.
Overloading vs. Overriding
- if a “subclass” has a method with the exact same signature as in the “superclass”, we say the subclass override the method
- Methods with the same name but different signatures are overloaded
Dynamic method selection only happens for overridden methods. Not happen for overloaded methods
1 | public static void peek(List61B<String> list) { |
Java extends
What would be extended
- When a subclass extends parent class, son-class inherits all members of father-class. “Members” includes:
- All instances and static variables
- All methods
- All nested classes
-
Constructors are not inherited, and private members cannot be directly accessed by subclasses.
-
Java requires that all constructors must start with a call to one of its superclass’s constructors. For example: there are two classes:
1 | public class Human{...} |
If we run the code below:
1 | TA Christine = new TA(); |
Java will automatically make a call to the superclass’s no argument constructor for us.
or we can use super keyword:
1 | public VengefulSLList() { |
Notice that the implicit call only inference the no-argument super constructor.
Every class in Java is a descendant of the Object class.
Casting
.hashcode() in Java
All object in java must implement a .hashCode() method.
All classes are hyponyms of Object
. And Default implementation simply returns the memory address of the object.
How to deal with negative hash code
Java uses Math.floorMod to deal with negative hashcode like below:
And following are the Java hash tables workflows:
- Warning #1: Never store objects that can change in a HashSet or HashMap!
- If an object’s variables changes, then its hashCode changes. May result in items getting lost.
- Warning #2: Never override equals without also overriding hashCode.
- Can also lead to items getting lost and generally weird behavior
- HashMaps and HashSets use equals to determine if an item exists in a particular bucket.