[ ^ CSE 341 | section index | next -->]

CSE 341 -- 27 Apr. 2000

Inheritance

Java presents two kinds of inheritance:

If A extends B, then A has:

  1. all the methods and fields of B,
  2. minus any methods that A overrides from B,
  3. plus any methods or fields that A defines.
If A and B have a field of the same name and type, then A's member hides B's member (this is usually bad practice). If A and B have a method of the same name and profile, then A's member overrides B's member.

Member lookup starts in the current object's class, then proceeds up the superclass tree. The super keyword defines a reference that begins member lookup in the direct superclass of the current object, but it's dangerous:

class Dog { boolean bites = false; boolean barks() { return true; } boolean callBarks() { return barks(); } } class PitBull extends Dog { boolean bites = true; boolean barks() { return false; } boolean superBites() { return super.bites; } boolean superBarks() { return super.callBarks(); } public static void main(String[] args) { Dog pooch = new Dog(); PitBull mauler = new PitBull(); System.out.println( pooch.barks() + ", " + mauler.barks() + ", " + mauler.superBites() + ", " + mauler.superBarks() ); } } Output: true, false, false, false

Last modified: Wed Apr 26 16:04:48 PDT 2000