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
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void peek(List61B<String> list) {
System.out.println(list.getLast());
}
public static void peek(SLList<String> list) {
System.out.println(list.getFirst());
}

SLList<String> SP = new SLList<String>();
List61B<String> LP = SP;
SP.addLast("elk");
SP.addLast("are");
SP.addLast("cool");
peek(SP); // execute the second peek() method
peek(LP); // execute the first peek() method

Java extends

What would be extended

  1. 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
  1. Constructors are not inherited, and private members cannot be directly accessed by subclasses.

  2. Java requires that all constructors must start with a call to one of its superclass’s constructors. For example: there are two classes:

1
2
3
public class Human{...}

public class TA extends 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
2
3
4
public VengefulSLList() {
super();
deletedItems = new SLList<Item>();
}

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.