How does Java match overloaded methods
When matching overloaded methods, Java checks for:
When is instanceof true?
a instanceof b. True if A is an instance of B, a subclass of B, or a class which implements the B interface (directly or indirectly)
Instanceof causing a compilation error?
If the compiler knowns that A can never be B. (Except when B is an interface. Even if your class A is final, you can still check instanceof interface. This is because you could have a subclass which implements the interface and this only gets checked at runtime)
Virtual method invocation
This is when we invoke regular non-static methods. The reason it virtual method invocation is because Java can look for overriden methods rather than the ones in the class the compiler says we have.
@Override
For @Override to work correctly, the method must be doing one of these:
* Implementing from an interface
* Overriding a superclass method
* Overriding hashCode, equals, toString()
Otherwise there will be a compilation error
Equals
Signature is public boolean equals(Object obj). If you use anything other than Object it is an overloaded method (not overriden).
Rules for overriding Equals
Overriding hashCode
A hashCode is a number which puts instances of a class into a finite number of categories. (Makes it easier to sort in a HashMap).
Enum values
.values() returns an array of all the values
Enum ordinal
.ordinal() is the int value that corresponds to the order the enum was declared. But you can’t compare enum to int, so watch out for this.
Enum valueOf
.valueOf(“”) returns the enum value of the exact match. Note it is case-sensitive. If it can’t find the enum value it will throw an IllegalArgumentException.
Enums in a switch statement
Needs to be just the ENUM value, can’t compare to int ordinal, or String values
Semi-colon in enums
Semi-colon is needed at the end of the enums if there is anything other than just the enum values
Enum constructors
The constructor is called once when you first call any Enum value.
Adding abstract methods to enums
Can add an abstract method into an enum, but then all enums must override this otherwise there will be a compilation error.
Member inner classes
Same variable names in inner class
A > B > C nesting with all having a variable x
If you’re calling from deepest level C:
* this.x will be C.x
* B.this.x will be B.x
* A.this.x will be A.x.
If you’re trying to get the x from C, but you’re in in B, this won’t work
Instantiating member inner classes
A a = new A(); A.B b = a.new B(); (Note: could have used the reference B here since B is a member of A) A.B.C c = b.new C(); (Note: Here we have to reference the full path to C since C is not a member of A).
Inner interfaces
Can be private
e.g. Can only be referred to from outer class
Local inner classes
Effectively final
Anonymous inner classes
Static nested classes