Chapter 1: Advanced Class Design Flashcards
How does Java match overloaded methods
When matching overloaded methods, Java checks for:
- Exact match
- Match by superclass
- Converting to a larger primitive
- Converting to autoboxed
- Varargs
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
- x.equals(x) == true
- x.equals(y) y.equals(x) both true or both false
- transitive x.eq(y) y.eq(z) then z.eq(x)
- must be consistent, so you can do it multiple times with the same result
- x.eq(null) == false. Note: Shouldn’t throw NPE!
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).
- Common not to include Boolean or ‘char’ values
- Within the same program, the result of a hashCode must not change. (i.e. don’t include variables which are likely to change)
- Can use a subset of variables which equals() uses
- hashCode() results don’t need to be unique when called on unequal results
- Common to multiply by a prime number to make the hashCode more unique
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.