1 / 9

Understanding Inheritance in Object-Oriented Programming: Concepts and Examples

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.

sirvat
Télécharger la présentation

Understanding Inheritance in Object-Oriented Programming: Concepts and Examples

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPSC 233 Tutorial Xin Mar 14, 2011

  2. Inheritance • super class – sub class • generic – specific • sub class inherits • non-private attributes • non-private methods • sub class defines new attributes & methods

  3. UML representation • Hollow triangle

  4. Gramma public class superClass { // … } public classsubClassextendssuperClass { // Definition of subclass – only what is unique to subclass }

  5. 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)

  6. Example 1

  7. Example -> use of super

  8. 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

  9. Example 3 type casting

More Related