Inheritance Lakshmish Ramaswamy Type Compatibility employee E new
Inheritance Lakshmish Ramaswamy
Type Compatibility employee E = new employee (…); person P = E; P. raise(0. 1); \ raise is a method in employee class that increases the salary • P. raise() is illegal although P is assigned to an employee object • At compile time, only visible members of static type can appear after dot operator
Casting • Casting changes the static type of object ((employee) P). raise(0. 1) is legal • Makes the static type of reference left of operator employee • If casting is impossible (completely different hierarchies) compiler complains • What if P is assigned to a student object? – Class. Cast. Exception • Use instanceof before you cast
Overriding and Overloading • Method overriding requires same method signature & same return type; – original method inherited from its superclass • Overloading requires different method signatures, but method name is same – parameters must be different in type and/or number • Method can be overloaded in same class or subclass • Overriding and overloading can used in conjunction
Compatibility of Array Types • Inheritance for aggregate types poses problems person [ ] arr = new employee [5]; student s = new student(…); arr[0] = s; • Code compiles • But arr[0] is referencing an employee but student IS-NOT-A employee • Each array keeps track of objects it is supposed to store • JVM will throw an Array. Store. Exception if incompatible type is inserted into array
Covariant Return Types • Prior to Java 5 overridden methods in subclass were required to have same return type as that of superclass method • Since Java 5 the return type of overridden method only needs to be type compatible with the base class method public person make. Copy(); // in person class public employee make. Copy(); // in employee subclass
- Slides: 6