CAP477 · Unit 2: Object-oriented programming
Overloading, overriding and dynamic dispatch
8 practice questions
Key points
- Overloading: compile time, by parameter types; override: run time, by object type
- Static methods and fields are not overridden
- Downcast can throw ClassCastException; use instanceof
- Parent constructor calling an overridden method sees default field values
Compile-time (static) polymorphism = overloading: same method name, different parameter lists in one class. The compiler picks the version from the argument types, in this order: exact match, widening (byte/char -> int), boxing, varargs. With f(int), f(long), f(double), f(Object): f(5) -> int, f(5L) -> long, f(5.0) -> double, f("s") -> Object, f('c') -> int, and a byte argument -> int. With f(Object) and f(String), f(null) picks the most specific (String). With g(long) and g(Integer), g(5) picks long (widening beats boxing). Changing only the return type is not overloading.
Run-time (dynamic) polymorphism = overriding: a subclass redefines an inherited instance method with the same signature. The version run depends on the actual object type, not the reference type: Sh s = new Ci(); s.draw(); runs Ci.draw. Rules: same name and parameters, return type same or covariant (a subtype), access not weaker, @Override makes the compiler check it. A method with a different parameter type (m(long) versus m(int)) is an overload, not an override, so Pa p = new Ch(); p.m(1) runs Pa.m.
What is not dynamic: static methods (hidden, resolved by reference type), fields (reference type), and private/final methods.
Upcasting (Pa p = new Ch()) is implicit and safe; downcasting needs a cast and fails with ClassCastException if the object is not that type. Guard with instanceof (pattern: if (a instanceof Dog d)).
Trap: a parent constructor that calls an overridden method runs the child's version before the child's fields are initialised (it sees 0/null).
Exam pitfall: overload picks by reference type at compile time; override by object type at run time.
Try two questions
Pa has static void s() and instance void i(); Ch redefines both. For Pa p = new Ch(); p.s(); p.i(); the output is:
- Ch.s then Pa.i
- Pa.s then Pa.i
- Ch.s then Ch.i
- Pa.s then Ch.i
Show the answer
D. Static methods are hidden, not overridden: Pa.s then Ch.i.
With overloads f(Object) and f(String), f(null) calls:
- f(Object)
- It throws NullPointerException
- f(String)
- Neither; ambiguous error
Show the answer
C. The most specific applicable method is chosen: String.