90 likes | 227 Vues
This tutorial covers key concepts of inheritance in object-oriented programming, focusing on the relationship between superclasses and subclasses. It illustrates how subclasses inherit attributes and methods from their superclasses, explains the significance of non-private attributes, method overriding, and polymorphism. The tutorial also distinguishes between method overriding and overloading, and highlights important keywords such as 'this' and 'super' in context. Examples demonstrate type casting within a class hierarchy and provide insights into best practices and potential pitfalls.
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