DEV Community

EL HADDAD Mohamed
EL HADDAD Mohamed

Posted on

2 Tricky Java Quirks I Discovered While Preparing for the OCP Java SE 21 Exam

While diving deep into my OCP Java SE 21 preparation, I stumbled upon two fascinating edge cases that are easy to miss during standard application development.

Here is what happened when I experimented with Records and the super keyword.

1-You Can't Name Record Components Anything You Want

In Java Records, the compiler automatically generates accessor methods using the exact name of each record component. I decided to test what happens if I name a component toString:

// ❌ Compilation Error!
public record User(String toString) {}

Enter fullscreen mode Exit fullscreen mode

Why does this fail?
Java explicitly prohibits naming record components after zero-parameter methods in java.lang.Object (such as toString, hashCode, equals, getClass, clone, finalize, notify, notifyAll, wait).

Because a record component named toString would require generating an accessor method toString(), it creates a naming collision with the inherited Object.toString() method contract, triggering a compilation error immediately.


2. Why super.equals(this) is true

To test how Java handles instance references in memory, I ran this test inside a standard class:

public class ReferenceTest {
    public void evaluate() {
        System.out.println(super.equals(this)); // Output: true
    }

    public static void main(String[] args) {
        new ReferenceTest().evaluate();
    }
}

Enter fullscreen mode Exit fullscreen mode

Why does it return true?
super is not a distinct object in memory. It is simply a keyword that refers to the current instance (this), while instructing the compiler to bypass overridden methods and use the superclass implementation instead.

When calling super.equals(this), it invokes Object.equals(Object obj). The default implementation in Object performs a reference check (this == obj). Since super and this point to the exact same object reference, the result evaluates to true.

Top comments (1)

Collapse
 
mcptokensaver profile image
MCP Token Saver

good writeup. the before/after numbers are what convinced me to try it.