Skip to content

Instantly share code, notes, and snippets.

@beshkenadze
Created September 26, 2024 14:45
Show Gist options
  • Save beshkenadze/356214f1f34b0a5becc46c42ba7abf79 to your computer and use it in GitHub Desktop.
Save beshkenadze/356214f1f34b0a5becc46c42ba7abf79 to your computer and use it in GitHub Desktop.
// Parent interface
interface IParent {
name: string;
value: number;
getInfo(): string;
}
// Child interface extending the parent
interface IChild extends IParent {
childSpecificMethod(): void;
}
// Parent class
class Parent implements IParent {
private _name: string;
private _value: number;
constructor(name: string, value: number) {
this._name = name;
this._value = value;
}
get name(): string {
return this._name;
}
set name(newName: string) {
this._name = newName;
}
get value(): number {
return this._value;
}
set value(newValue: number) {
this._value = newValue;
}
getInfo(): string {
return `Name: ${this._name}, Value: ${this._value}`;
}
// Method to change multiple parameters at once
updateInfo(name?: string, value?: number): void {
if (name !== undefined) this._name = name;
if (value !== undefined) this._value = value;
}
}
// Child class
class Child extends Parent implements IChild {
private _childProperty: string;
constructor(name: string, value: number, childProperty: string) {
super(name, value);
this._childProperty = childProperty;
}
get childProperty(): string {
return this._childProperty;
}
set childProperty(newProperty: string) {
this._childProperty = newProperty;
}
childSpecificMethod(): void {
console.log("This is a child-specific method");
}
// Override parent method
getInfo(): string {
return `${super.getInfo()}, Child Property: ${this._childProperty}`;
}
}
// Usage example
const parent = new Parent("ParentName", 100);
console.log(parent.getInfo()); // Output: Name: ParentName, Value: 100
parent.updateInfo("NewParentName", 200);
console.log(parent.getInfo()); // Output: Name: NewParentName, Value: 200
const child = new Child("ChildName", 50, "ChildProp");
console.log(child.getInfo()); // Output: Name: ChildName, Value: 50, Child Property: ChildProp
child.name = "NewChildName";
child.value = 75;
child.childProperty = "NewChildProp";
console.log(child.getInfo()); // Output: Name: NewChildName, Value: 75, Child Property: NewChildProp
child.childSpecificMethod(); // Output: This is a child-specific method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment