Understanding instanceof
The instanceof
operator is a powerful tool to determine if an object is an instance of a specific class or interface.
- Checks if the left operand is the same class, interface, or a subclass as the right operand.
- Returns
false
if the left operand isnull
. - If the operands are not in the same class hierarchy, the code will not compile.
Correctly Implementing equals()
, hashCode()
, and toString()
equals()
The equals()
method is used to compare objects for equality:
- Declared as
public boolean equals(Object obj)
. - Returns
false
if called withnull
or an object of the wrong type.
hashCode()
The hashCode()
method generates a hash code for an object:
- Declared as
public int hashCode()
. - Should use some or all instance variables used in
equals()
for consistency.
toString()
The toString()
method provides a string representation of an object:
- Declared as
public String toString()
. - Can return any string representation of the object.
Working with Enums
Enums represent a fixed set of constants in Java.
- Enums can list values, and the semicolon after the values is optional if nothing follows.
- Can have instance variables, constructors, and methods.
- Constructors must be
private
or package-private. - Enums can define methods either at the top level or within individual values.
- If an enum declares an abstract method, each value must implement it.
Understanding Nested Classes
Java supports different types of nested classes, each with unique behaviors:
Member Inner Classes
- Instantiated with
outer.new Inner()
.
Local Inner Classes
- Scoped to the end of the current block.
- Cannot have static members.
Anonymous Inner Classes
- Limited to extending a class or implementing one interface.
- The statement creating an anonymous inner class must end with a semicolon.
Static Nested Classes
- Cannot access instance variables of the enclosing class.
Using Imports and Static Imports
Imports help organize code by bringing external classes and static members into scope:
- Classes can be imported by name or wildcard (
*
). - Wildcards do not include subdirectories.
- In conflicts, class name imports take precedence.
import static
is used for static members (methods or variables).
Rules for Method Overriding and Overloading
Overriding Methods
- The method must have the same signature as in the parent class.
- Must be at least as accessible as the parent method.
- Cannot declare new or broader exceptions.
- Can use covariant return types.
- The
@Override
annotation is optional but recommended.
Overloading Methods
- Overloaded methods have the same name but different argument lists.
0 Comments