Inheritance
Java presents two kinds of inheritance:
- extends: Implementation inheritance
- implements: Interface inheritance
If A extends B, then A has:
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.
- all the methods and fields of B,
- minus any methods that A overrides from B,
- plus any methods or fields that A defines.
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