Object Oriented

Inheritance

Java

 

Inheriting

Java 8
// Person.java file
class Person {
  public String name;
  
  public Person(String name) {
    this.name = name;
  }
  
  public void greet() {
    System.out.println("Hi! I'm " + name);
  }
}

// Teacher.java file
class Teacher extends Person {
  public int grade;
  
  public Teacher(String name, int grade) {
    super(name);
    this.grade = grade;
  }
}

Classes can inherit methods and properties of another class.

In this example, the Teacher class inherits the name property and greet() method from the Person class.

Teacher teacher1 = new Teacher("Alice", 2);

String name = teacher1.name;  // Alice
teacher1.greet();             // Hi! I'm Alice

You need to explicitly call the Parent (Person) Constructor from the children (Teacher) Constructors using super.

 

Overriding Methods

Java 8
// Person.java file
class Person {
  public String name;
  
  public Person(String name) {
    this.name = name;
  }
  
  public void greet() {
    System.out.println("Hi! I'm " + name);
  }
}

// Teacher.java file
class Teacher extends Person {

    public Teacher(String name) {
        super(name);
    }

    @Override
    public void greet() {
        System.out.println("Hello! I am " + name);
    }

    public void greet2() {
        super.greet();
    }
}

Inherited methods from a parent class can be overridden in the children's classes.

Overriding methods is more like extending the definition rather than replacing them.

Teacher teacher1 = new Teacher("Alice");

teacher1.greet();   // Hello! I am Alice
teacher1.greet2();  // Hi! I'm Alice

In order to access parent overriden methods, use super keyword.

@Override is a Java annotation. It is a hint to compiler that you indeed want to override an existing method.

Using @Override is optional but recommended.