Explain that question "What is method overriding, and what rules apply to it?" using TS…
- User
Explain that question "What is method overriding, and what rules apply to it?" using TS and Angular(where it's possible) like in a tutorial.
- Assistant
Explain that question "What is method overriding, and what rules apply to it?" using TS and Angular(where it's possible) like in a tutorial.
Method overriding is a fundamental concept in object-oriented programming (OOP) that allows a subclass (child class) to provide a specific implementation of a method that is already defined in its superclass (parent class). In TypeScript, which supports OOP paradigms, method overriding enables developers to create more specialized and reusable code. This tutorial will explain method overriding and the rules that apply to it in the context of TypeScript and Angular.
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The subclass's method overrides the superclass's method, allowing the subclass to customize or completely replace the behavior of that method.
Key Points:
TypeScript, being a typed superset of JavaScript, brings in OOP features like classes, interfaces, inheritance, and access modifiers, making method overriding possible.
In TypeScript:
extends keyword is used to create a subclass.When overriding methods in TypeScript, several rules must be followed:
Method Signature: The method in the subclass must have the same name and parameter list as in the superclass.
Return Type: The return type must be the same or a subtype (covariant) of the return type declared in the superclass.
Access Modifiers:
public, the subclass cannot override it with private or protected.Optional Parameters:
super Keyword:
super.methodName() if you need to extend the original functionality.Final Methods (Not in TypeScript):
final, preventing overriding. TypeScript does not have a final keyword, but you can simulate it using sealed classes or comments.Let's explore method overriding with a simple example.
class Animal {
public makeSound(): void {
console.log('Generic animal sound');
}
}
class Dog extends Animal {
public makeSound(): void {
console.log('Bark!');
}
}
const myDog = new Dog();
myDog.makeSound(); // Output: Bark!
Explanation:
Animal class has a makeSound method.Dog class extends Animal and overrides the makeSound method.makeSound is called on an instance of Dog, the overridden method in Dog is executed.Access modifiers control the visibility of class members. In method overriding, the subclass cannot reduce the visibility of the overridden method.
class Vehicle {
protected startEngine(): void {
console.log('Engine started');
}
}
class Car extends Vehicle {
public startEngine(): void {
console.log('Car engine started');
}
}
const myCar = new Car();
myCar.startEngine(); // Output: Car engine started
Explanation:
Vehicle class has a protected method startEngine.Car class overrides startEngine and changes its visibility to public.public is less restrictive than protected.Invalid Example (Reducing Visibility):
class Appliance {
public turnOn(): void {
console.log('Appliance is on');
}
}
class WashingMachine extends Appliance {
protected turnOn(): void {
console.log('Washing machine is on');
}
}
// Error: Property 'turnOn' in type 'WashingMachine' is not assignable to the same property in base type 'Appliance'.
// Type '() => void' is not assignable to type '() => void'.
// Types of property 'turnOn' are incompatible.
Explanation:
public method with a protected one is not allowed, as it reduces visibility.In Angular, method overriding can be applied when extending components, services, or other classes. A common use case is when you create a base component or service and then extend it to create specialized versions.
Angular components have lifecycle hooks like ngOnInit, ngOnDestroy, etc. You can override these methods in derived components.
Base Component:
import { OnInit } from '@angular/core';
export class BaseComponent implements OnInit {
public ngOnInit(): void {
console.log('BaseComponent initialized');
}
}
Derived Component:
import { Component } from '@angular/core';
import { BaseComponent } from './base.component';
@Component({
selector: 'app-child',
template: '<p>Child Component</p>',
})
export class ChildComponent extends BaseComponent {
public ngOnInit(): void {
super.ngOnInit();
console.log('ChildComponent initialized');
}
}
Explanation:
ChildComponent extends BaseComponent and overrides ngOnInit.super.ngOnInit() to invoke the base class method, then adds additional functionality.ChildComponent is initialized, the console output will be:
BaseComponent initialized
ChildComponent initialized
Overriding Services:
You can also override methods in services.
Base Service:
export class LoggerService {
public log(message: string): void {
console.log('Default Logger:', message);
}
}
Custom Logger Service:
import { Injectable } from '@angular/core';
import { LoggerService } from './logger.service';
@Injectable({
providedIn: 'root',
})
export class CustomLoggerService extends LoggerService {
public log(message: string): void {
// Optionally, call the base method
// super.log(message);
// Custom implementation
console.log('Custom Logger:', message);
}
}
Explanation:
CustomLoggerService overrides the log method to provide a different logging mechanism.Method overriding in TypeScript allows subclasses to provide specific implementations of methods defined in their superclasses. This enables polymorphism and code reuse, which are central to OOP.
Key Takeaways:
super to invoke the superclass's method if needed.By understanding and applying the rules of method overriding, you can write more effective and maintainable TypeScript and Angular applications.
Not yet included in a published release.