class Prev {
constructor(name = "Chaitanya") {
this.name = name;
}
// In JavaScript, method overloading is not supported directly.
// So, we can handle it using conditional logic inside the method.
getName(n) {
if (n !== undefined) {
console.log(`Overloaded method called with argument: ${n}`);
} else {
console.log(`My name is => ${this.name}`);
}
}
}
// Inheritance Example
class Next extends Prev {
constructor(name) {
// Referring to the parent class constructor using super
super(name); // You can pass arguments to the parent constructor
}
// Method overriding: Overriding the getName method in child class
getName() {
console.log(`My name is => ${this.name} from Next`);
}
// Private method using `#` (ES2022 standard)
static #privateMethod() {
console.log("This is a private method and cannot be accessed directly.");
}
// A public method to demonstrate calling the private method
static accessPrivateMethod() {
this.#privateMethod(); // Call the private method from within the class
}
}
// Creating an instance of Prev class
const prev = new Prev();
prev.getName(); // Calls default getName method
prev.getName("XXXXXX"); // Demonstrates method overloading using argument check
// Creating an instance of Next class (Inheritance)
const next = new Next("Alex");
next.getName(); // Calls the overridden method in Next class
// Trying to call the private method
// next.#privateMethod(); // Error: Private method cannot be accessed directly
Next.accessPrivateMethod(); // Correct way to access private method
// Exporting the classes (useful for Node.js)
module.exports = { Next, Prev };