February 2, 2021
Lecture slides
Forrige forelesning (subklasser og arv) Neste forelesning (arv og interface)
Lecture outline:
- Virtuelle metoder, eller polymorfi
- Arv vs. komposisjon
- Konstruktører i sub-klasser
- Typekonvertering
Polymorfi (Polymorphism)
- A virtual function or virtual method (also known as polymorphic) is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature to provide the polymorphic behavior.
- All the methods in Java are virtual, if they are not declared
final
.
- The overriding method needs to have the exact same signature and name as the super-class method - otherwise the program treats them as two different methods.
@Override
annotation is used to explicitly tell the program that the method is being overridden. This is useful for two reasons:
- When compiling, the program will tell you if some of the overriding methods don't match and point to them.
- The code becomes more readable.
- If we define an object of a sub-class, but declare it as an object of a super-class, and then try to call the overridden method, the compiler will approve of it and treat it as a super-class method, but the run-time system will perform the sub-class method.
- You can use a key-word
super.method()
to refer to the super-class method within the overriding one.
- Super-class variables can also be overridden, but that's a no-no, cuz it reduces the code readability and leads to unpredictable behavior.
Override vs. overload
- Overriding happens when the two methods have the same signature
- Overloading happens when the two methods have different signatures (e.g. the name and data type is the same, but the parameters are different).