Inheritance in OOP

Inheritance is a programming concept where new classes can use existing attributes and methods from other classes. These new classes can then be referred to as subclasses

For example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Animal {
  private String _sound;

  public String whatSound() {
    return this._sound;
  }
}

class Dog extends Animal {
  private String _sound = "Woof";
}

// ------------------------------ //
//              ...
// ------------------------------ //

Dog d = new Dog();
d.whatSound();

Method Overriding

  • Argument list should be the same as that of the overridden method
  • The return type must be the same, or a subtype
  • Access level cannot be more restrictive than the overridden method's access level
  • Static methods cannot be overridden

Good Practices for Inheritance

Inheritance Relationships

Click here

Types

Consider a class B that extends class A - we are able to represent an instance of B as its parent type.
i.e. A newObj = new B().

This can be possibly bad, as whilst newObj is of type A, the object contains methods for type B