Java
What are Anonymous Classes in Java?
Summary
- Anonymous class is an expression
- Declare and instantiate a class at the same time
- Do not have name
- It consists of new operator
- Could implement interface or extend class
- Because it is an expression, statement should end with semicolon
Example
interface Print {
public void display();
}
// Anonymous class
Print search = new Print() {
String name = "Waheguru";
public void display() {
System.out.println("Oneness " + name);
}
};
Resources
What is difference between Java Comparator and Comparable?
Common
- Both interfaces are available to define custom sorting
- Class need to implement interface and override method
- Both are Functional Interfaces. Meaning lambda expression can be provided to have different type of sorting in different situations
- Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Comparator
int compare(T o1, T o2)
- Compares its two arguments for order
Comparable
int compareTo(T o)
- Object comparing itself with another object
Resources