Now, in my Inherited class I can create its own constructor overriding the constructor in the parent class:
As you observe, in the constructor of the inherited class - i call the super() function. The super function indicates that I am calling the constructor of the parent class. Since, the constructor of the parent class expects a input. Hence, we pass an input to the super("Visakhapatnam") function.
But, while instantiating the child class - we do not pass in any arguments. This is because, the constructor in the child class does not expect any input arguments.
class City {
public name:string;
private type: string;
protected elevation: number;
constructor(name:string) {
this.name = name;
this.type = "city";
this.elevation = 505;
}
setElevation(elevation:number){
this.elevation = elevation;
console.log("new elevation = "+this.elevation);
}
getElevation(){
console.log(this.elevation);
}
setType(type:string){
this.type = type;
console.log("new type = "+this.type);
}
printType(){
console.log(this.type);
}
}
const city = new City("Hyderabad");
console.log(city);
city.getElevation();
city.setElevation(506);
city.printType();
city.setType("Metro");
city.printType();
class Visakhapatnam extends City{
name = "Visakhapatnam";
protected elevation = 45;
constructor(){
super("Visakhapatnam");
}
}
const cityVisakha = new Visakhapatnam();
console.log(cityVisakha);
console.log(cityVisakha.name);
cityVisakha.setType("Town");
console.log(cityVisakha.printType());
console.log(cityVisakha.getElevation());
console.log(cityVisakha);
As you observe, in the constructor of the inherited class - i call the super() function. The super function indicates that I am calling the constructor of the parent class. Since, the constructor of the parent class expects a input. Hence, we pass an input to the super("Visakhapatnam") function.
But, while instantiating the child class - we do not pass in any arguments. This is because, the constructor in the child class does not expect any input arguments.
No comments:
Post a Comment