Defining a variable with the same name in a subclass

  • If a subclass defines a variable x with the same name as its superclass:

    • the name x will refer to the variable in the subclass

      I.e.:

      • The variable x in the subclass will "overshadow" (= hide) the variable in the superclass

    • The variable x in the superclass can accessed in the subclass using:

         super.x 
      

      (or through a non-overridden method)

  • Warning:

    • It's a terrible idea to "override" variables !!!

DEMO: demo/04-inheritance/90-same-var-in-subclass

Multiple inheritance

  • Java allows a class to inherit from only one (= 1) superclass

  • C++ on the other hand can inherit from multiple class...

    ... and made things very complicated...

  • Example:

    • If 2 parent classes has a variable with the same name (but different type), what do you inherit ?

  • Java does implement some features of multiple inheritance through:

    • Interface

    I.e.:

    • A class can have multiple "parent "interfaces"

    • But these parent "interfaces" must be "completely empty"
      (empty = no variables and contains only method declarations)

    We will be discussing the interface concept soon