Sobes.tech
Junior — Middle

How can you call a parent class method from a derived class?

sobes.tech AI

Answer from AI

To call a parent class method from a subclass, the super keyword is usually used. It allows you to access methods or constructors of the base class.

For example, in JavaScript:

class Parent {
  greet() {
    console.log('Hello from Parent');
  }
}

class Child extends Parent {
  greet() {
    super.greet(); // call to parent method
    console.log('Hello from Child');
  }
}

const child = new Child();
child.greet();
// Output:
// Hello from Parent
// Hello from Child

In other languages, such as Java, super is also used:

class Parent {
    void greet() {
        System.out.println("Hello from Parent");
    }
}

class Child extends Parent {
    @Override
    void greet() {
        super.greet(); // call to parent method
        System.out.println("Hello from Child");
    }
}

Thus, super allows explicitly calling a method or constructor of the base class from a subclass.

How can you call a parent class method from a derived… - sobes.tech