Lecture 3 Summary (Polymorphism) - nus-cs2030/2122-s1 GitHub Wiki
Lecture 3 Summary
Liskov Substituion Principle (LSP)
- if S is a subclass of T, object of type S can replace type T objects without changing the desirable property of the program.
Polymorphism
- Many forms
- Sub-type can be passed in as arguments for super-type parameters
- You can convert from sub-type to super-type but not other way round
Compile-Time type
- The type in which the variable is declared
- Restricts the methods it can call during compilation
Run-time type
- The type of the object that the variable is point to
- Determines the actual method called during runtime
A variable's compile-type is determined at compile time; its run-time type varies depending on object assigned to it
Testing object equality
- Comparing two objects using the == operator returns true only if both refers to the same object instance
(Same for the inherited Object.equals(Object) method)
- However, for String objects, the == compares if the String objects are the same instance while the String.equals method compares if the String content is the same
Overloading
Same method name different argument type. Will be called when the method is called with the corresponding argument type
Static Binding
The compile-time type decides which overloaded method to call during compilation
Overriding
Same method name and argument types. Will be the method called during run-time.
Dynamic Binding
Exact method to invoke is not known until runtime