We want to make the java compiler understand that both the employee objects e1 and e2
are logically same.
We override the equals method to make compiler understand that entities are logically same
A child class methods cannot have more security than parent class for same method.
Eg: if a method is public in parent and child class makes it private it will give an compile time
error.
But opposite is valid case , we can make a child class method more accessible than its
parent method
The above method overriding gives compile time error due to :
● If we pass(2,3) without last method , the type promotion of 3 int to long will take and
program will run without error.
● If we uncomment last method , compiler error is reised as it cannot decide which
parameter to promote to long.
Comparable and Comparator interface:
Comparable:
● The custom class needs to implement this interface
● Override the compareTo() method
● It is implemented directly in class defining its natural ordering
● Ideal approach when there is a clear single way to order objects of the class.
● Pros:
○ Clean and intuitive implementation
○ Natural ordering built into the class
○ No additional classes needed
○ Automatically used by [Link]()
● Cons:
○ Limited to single sorting criteria
○ Cannot change sorting logic without modifying class
○ Tightly couples sorting logic with class implementation
Comparator:
● Allows you to define external sorting logic
● This approach is more flexible as you can create multiple comparators for different
sorting needs.
● The compare() method works similarly to compareTo(), but its implemented in a
separate class
● Pros:
○ Supports multiple sorting criteria
○ Separates sorting logic from class implementation
○ More flexible and maintainable
○ Can create multiple comparators for different needs
● Cons:
○ Requires additional classes
○ Slightly more verbose
○ Need to pass comparator as parameter