Monday, February 11, 2013

SCJP - Overriding vs overloading

Overriding Rules:
Access - cannot have a more restrictive access.
Argument list - must match exactly
Return type - the same or a subtype (this is the called covariant return, new in Java 5)
Exceptions - Can throw any unchecked (runtime) exceptions; cannot throw checked exceptions that are new or broader (must by the same, a subtype or none); can throw less or narrower.

private, final or static method cannot be overriden:
private methods are not visible in the derived class, so if the method has the same signature in the derived class, then it is a new method - no compilation failure.
final methods mean that they cannot be redefined, or a compiler error is generated.
static method cannot be overriden because they do not belong to the instance.
  • When a child class contains the same instance method as a parent class instance method (assuming all the rules of method overriding are followed), the child class method overrides the parent class method.
  • When a child class contains a static method that is the same as a static method in the parent, this child method hides the parent class method.
  • A child class cannot contain a nonstatic version of a static method in its parent class. Neither can a child class contain a static method with the same version of a nonstatic method in the parent. Either of these situations generates a compiler error.

In simpler terms, instance methods are overridden and static methods are hidden.
The overriden call is executed in the object type (runtime).

Overloading Rules:
Access - can change
Argument list - Must change
Return type - can change
Exception - can change

The overloaded call is executed in the reference type (compile time).




Information collected from:
SCJP: Sun Certified Programmer for Java Platform Study Guide: SE6 (Exam CX-310-065), Richard F. Raposa
SCJP Sun Certified Programmer for Java 6 Exam 310-065, Katherine Sierra and Bert Bates
A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition)

No comments:

Post a Comment