Page 1 of 1

Re: About Question enthuware.ocpjp.v17.2.3698

Posted: Sun Oct 20, 2024 10:19 pm
by dalvir
Hi

For the first option as given below:
----------------------------------------------------
record Student(int id, String... subjects){    
 @Override     
public int id(){  
       return 10;     }          

@Override     
public boolean equals(Object obj){       
  return false;     
}
}
-------------------------------------------------
first @Override annotation isn't making sense to me though it's compiling fine in IntelliJ.
AFAIK, direct supertype of this Student record is java.lang.Record which doesn't have any member method id(). Hence, Student record isn't overriding id() but declaring/defining it.
Can you please explain why first @Override annotation is not throwing any error?

Thanks

Re: About Question enthuware.ocpjp.v17.2.3698

Posted: Mon Oct 21, 2024 12:22 am
by admin
Because it is allowed by the specification. Section 9.6.4.4 @Override mentions where this annotation is valid and one of the conditions is:

Q is a record class (§8.10), and the method is an accessor method for a record component of Q (§8.10.3).
It also explains the reason:
The clause about a record class is due to the special meaning of @Override in a record declaration. Namely, it can be used to specify that a method declaration is an accessor method for a record component. Consider the following record declaration:
record Roo(int x) {
@Override
public int x() {
return Math.abs(x);
}
}
The use of @Override on the accessor method int x() ensures that if the record component x is modified or removed, then the corresponding accessor method must be modified or removed too.

Re: About Question enthuware.ocpjp.v17.2.3698

Posted: Mon Oct 21, 2024 1:09 am
by dalvir
Thanks for pointing out. I appreciate.