Can JavaScript parent and child classes have a method with the same name?

Yes, JavaScript parent and child classes can have methods with the same name. This concept is called method overriding, where the child class provides its own implementation of a method that already exists in the parent class.

Method Overriding Example

class Parent {
    constructor(parentValue) {
        this.parentValue = parentValue;
    }
    
    // Parent class method
    showValues() {
        console.log("The parent method is called.....");
        console.log("The value is=" + this.parentValue);
    }
}

class Child extends Parent {
    constructor(parentValue, childValue) {
        super(parentValue);
        this.childValue = childValue;
    }
    
    // Child class method with same name - this overrides the parent method
    showValues() {
        console.log("The child method is called.....");
        console.log("The value is=" + this.childValue);
    }
}

var parentObject = new Parent(100);
parentObject.showValues();

var childObject = new Child(400, 500);
childObject.showValues();
The parent method is called.....
The value is=100
The child method is called.....
The value is=500

Calling Parent Method from Child

You can also call the parent method from within the child method using super:

class Parent {
    constructor(name) {
        this.name = name;
    }
    
    greet() {
        console.log(`Hello from parent: ${this.name}`);
    }
}

class Child extends Parent {
    constructor(name, age) {
        super(name);
        this.age = age;
    }
    
    greet() {
        super.greet(); // Call parent method first
        console.log(`Hello from child: I am ${this.age} years old`);
    }
}

const child = new Child("Alice", 10);
child.greet();
Hello from parent: Alice
Hello from child: I am 10 years old

Key Points

  • When a child class defines a method with the same name as the parent, it overrides the parent method
  • The child method is called instead of the parent method when invoked on child instances
  • Use super.methodName() to call the parent method from within the child method
  • Method overriding enables polymorphism in object-oriented programming

Conclusion

JavaScript allows method overriding where child classes can redefine parent methods. This enables customized behavior while maintaining the same interface across the inheritance hierarchy.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements