90 likes | 216 Views
CPSC 233 Tutorial. Xin Mar 14, 2011. Inheritance. super class – sub class generic – specific sub class inherits non-private attributes non-private methods sub class defines new attributes & methods. UML representation. Hollow triangle. Gramma. public class superClass { // … }
E N D
CPSC 233 Tutorial Xin Mar 14, 2011
Inheritance • super class – sub class • generic – specific • sub class inherits • non-private attributes • non-private methods • sub class defines new attributes & methods
UML representation • Hollow triangle
Gramma public class superClass { // … } public classsubClassextendssuperClass { // Definition of subclass – only what is unique to subclass }
Method overriding/polymorphism • Redefine a method with the same signature (name, parameters, and returned value) • As opposed to overloading, which defines methods with different signatures • this: pointing to the current object • super: pointing to the super class • super.method ( ) • super.attribute (shadowing, not good)
Reference Casting • public class SuperClass {} • public class SubClass extend SuperClass{} • SuperClass sup = new SubClass(); // ✔ no casting needed • SubClass sub = (SubClass) sup; // ✔ casting needed; sup must be an object of SubClass • SubClass sub2 = (SubClass) new SuperClass () // ✗ • Casting between different classes not in a hierarchy is not allowed