I am trying to understand the concept of Class Inheritance in PowerShell. I almost get everything works, just need someone to explain the error and the empty constructor that I accidentally found out.
I define a base class.
class Human {
[string]$name
[string]$gender
Human(){} # Comment out this line and hit error
Human($name, $gender)
{
$this.name = $name
$this.gender = $gender
}
[void]Speak()
{
Write-Host -ForegroundColor Green "I am a human"
}
}
Define Teacher class derived from Human class.
class Teacher : Human {
# Don't need to repeat $name & $gender if inherit from Human class
# Introduce new class property -> $subject
[string]$subject
Teacher($name, $gender, $subject)
{
$this.name = $name
$this.gender = $gender
$this.subject = $subject
}
# Overrides Speak() method in Human class
[void]Speak()
{
Write-Host -ForegroundColor Green "I am a $($this.subject) teacher"
}
}
$t1 = [Teacher]::new("Steven", 'Male', 'English')
$t1
$t1.Speak()
Instance $t1 works just fine with following output.
subject name gender
------- ---- ------
English Steven Male
I am a English teacher
I will get following output with an error message if comment out the Human(){}
in Human class. Though PowerShell still print output for $t1
and $t1.Speak()
. For the record, I am using PowerShell 7.4.2 on VS Code. And here is my reference for class inheritance.
MethodException:
Line |
8 | {
| ~
| Cannot find an overload for "new" and the argument count: "0".